找出较大的下一个数字组合 Next Permutation

来源:互联网 发布:python 字典 key 变量 编辑:程序博客网 时间:2024/05/16 00:32
问题: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

思路:先想测试用例,完善的输入用例要比代码重要。

特殊输入用例:

1、末尾是升序:523,只要交换最后两个数即可。

2、整体都是降序:321,需要对整个序列彻底逆置。

3、前面有升序,末尾是降序:13542,记住最后一个极大值点的左侧数(本例是3),

对末尾的降序从右向左找到第一个大于3的数(本例是4),

交换3/4,然后把原来降序的末尾排成升序。

针对上面提到的三种情况,需要做出对应的操作。

class Solution {public:    void nextPermutation(vector<int> &num) {                int n = num.size();        if(n <= 1)            return;        int mark = -1;                for(int i=0;i<n-1;i++)        {            if(num[i] < num[i+1])                mark = i;//记住最后的升序(最后一个极大值点的左边)        }if(mark == -1) //整体是降序:逆转排成最小的数字{            int left = 0;            int right = n-1;            while(left < right)                swap(num[left++], num[right--]);      }        else if(mark == n-2) //末尾是升序,交换最后即可        {            swap(num[mark], num[mark+1]);            return;        }        else //末尾不是升序,从右向左找出第一个大于num[mark]的数与其交换,其他的数排成升序        {            int right = n-1;            while(num[right] <= num[mark])                right--;            swap(num[mark], num[right]);            int left = mark+1;            right = n-1;            while(left < right)                swap(num[left++], num[right--]);                    }    }};


0 0