Next Permutation

来源:互联网 发布:2016健康大数据 编辑:程序博客网 时间:2024/04/24 14:55

Next PermutationFeb 25 '12

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. 从当前序列最尾端开始往前寻找两个相邻元素,令前面一个元素为*i,后一个元素为*ii,且满足*i<*ii;
2. 再次从当前序列末端开始向前扫描,找出第一个大于*i的元素,令为*j(j可能等于ii),将i,j元素对调;
3. 将ii之后(含ii)的所有元素颠倒次序,这样所得的排列即为当前序列的下一个排列。


class Solution {public:    void nextPermutation(vector<int> &num) {        int i = 0;        int k = num.size();                while(k-->=1)        {            if(num[k] > num[k-1])            {                i = k;                break;            }        }        int j= i-1;        k = num.size();        while(k-- != i-1)        {            if(num[k] > num[i-1]) {                j = k;                break;            }        }                  swap(num[i-1],num[j]);            reverse(num.begin()+i,num.end());    }};


60 milli secs



原创粉丝点击