[LeetCode]Next Permutation

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).code

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

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.遞歸

1,2,31,3,2it

3,2,11,2,3io

1,1,51,5,1class

思考:全排列的非遞歸函數。test

class Solution {
public:
    void Reverse(vector<int> &num,int begin,int end)
    {
        while(begin<end)
        {
            swap(num[begin++],num[end--]);
        }
    }
    void nextPermutation(vector<int> &num) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int len=num.size();
        if(len==0||len==1) return;
        int i,j;
        for(i=len-2;i>=0;i--)
        {
            if(num[i]<num[i+1])
            {
               for(j=len-1;j>i;j--)
               {
                   if(num[j]>num[i])
                   {
                       swap(num[i],num[j]);
                       Reverse(num,i+1,len-1);
                       return;
                   }
               }
            }
        }
        Reverse(num,0,len-1);
    }
};
相關文章
相關標籤/搜索