Next Permutation

来源:互联网 发布:js删除id 编辑:程序博客网 时间:2024/05/27 00:36
题目大意:
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) 对于任何数列,从右往左看,要想改变的一定是找那种递增着突然递减的那个值。 如:1,2,5,3,1. 那么要改变的值一定是2。因为2的右边的这个序列值已经是最大的了。

2) 将这个值2存下来 temp=2,然后对于2,5,3,1的这一段进行从小到大排序,得到1,2,3,5。

3) 对这个序列进行从尾到头遍历,若找到与temp一样的值,则将比2大的数3存入temp, 然后将3的位置开始到头的位置往后移动一位,最后将temp的值存入第一位,即可得到3,1,2,5。

我的代码:

 void nextPermutation(vector<int>& nums) {        int len = nums.size();        if(len < 2) return;        vector<int>:: iterator it = nums.begin();        int i = len-1;        for(; i>= 1; i--){            if(nums[i] <= nums[i-1])                continue;            else            break;        }        if(i == 0)            sort(it,nums.end());        else{            int temp = nums[i-1];            sort((it+i-1),nums.end());            int k = len-1;            for(; k >= i-1; k--){                if(nums[k]==temp){                    temp = nums[k+1];                    break;                }            }            for(int p = k; p >= i-1;p--){                nums[p+1] = nums[p];            }            nums[i-1] = temp;        }        return;            }



0 0