首页 > 技术文章 > [LeetCode]Next Permutation

Rosanna 2013-11-27 10:38 原文

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,31,3,2

3,2,11,2,3

1,1,51,5,1

思考:全排列的非递归函数。

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);
    }
};

  

推荐阅读