• <LeetCode OJ> 31. Next Permutation


    31. Next Permutation

    Total Accepted: 54346 Total Submissions: 212155 Difficulty: Medium

    Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

    If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

    The replacement must be in-place, do not allocate extra memory.

    Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
    1,2,3 → 1,3,2
    3,2,1 → 1,2,3
    1,1,5 → 1,5,1




    STL来做,秒杀

    class Solution {
    public:
        void nextPermutation(vector<int>& nums) {
            next_permutation(nums.begin(), nums.end());
        }
    };

    此题感觉没多大意思。不好高速想出规律:

    可是比較明显的规律是:

    1。升序为最小组合,降序为最大组合

    2,某一个数的下一个数,就是比他大的最小组合数。比方123,下一个比他大的最小组合就是132,必须从低位处理

    3,stl的处理就是从低位(数组末尾)開始找起,

    a)找到首个相邻的升序序列。将前一个数据与比其首次大的数交换(然后逆置后面的数)比方:123543为124533(首个升序3,5。可是4是首次比3大,则交换),此处的操作意义就是使数通过首个升序变大。

    b)显然此数不是大于原数的最小数,而且后面的数逆置后才是最小的,即124533为124335。so,done!

    //思路首先(不调用库函数):
    //举例:abc,acb,bac,bca,cab,cba
    class Solution {
    public:
        void nextPermutation(vector<int>& nums) {
            if(nums.empty() || nums.size()==1)
                return;
            vector<int>::iterator ite1=nums.end();
            ite1--;
            while(true)
            {
                vector<int>::iterator ite2=ite1;
                ite1--;//ite1始终在ite2前面一个位置(左边算作最前面)
                if(*ite1 < *ite2)//升序已经出现。接着又一次从后面找首个升序位置
                {
                    vector<int>::iterator itej=nums.end();
                    while(!(*ite1 < *--itej));
                    iter_swap(ite1,itej);//找到首个升序序列将其交换
                    reverse(ite2,nums.end());
                    return;
                }
                
                if(ite1==nums.begin())
                { 
                   reverse(nums.begin(),nums.end());
                   return;
                }
            }
        }
    };



    注:本博文为EbowTang原创,兴许可能继续更新本文。假设转载,请务必复制本条信息!

    原文地址:http://blog.csdn.net/ebowtang/article/details/50450861

    原作者博客:http://blog.csdn.net/ebowtang



    參考资源

    【1】侯捷。《STL源代码剥析》

  • 相关阅读:
    pku3225 区间
    pku2136 Vertical Histogram
    NOI2006 最大获利
    APIO2010 特别行动队
    停电两夜
    偷偷乐一把
    那些花儿...
    一件一块钱的小事
    web service 的Section=ResponseStatusLine 错误和skype
    杂谈
  • 原文地址:https://www.cnblogs.com/lytwajue/p/7088638.html
Copyright © 2020-2023  润新知