31.Next Permutation

来源:互联网 发布:c语言点滴 epub 编辑:程序博客网 时间:2024/05/01 11:56

Promblem:

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


题意为寻找比当前序列大的新序列。

那什么叫比前序列大呢?其实可以把数字序列理解为多位数字,对于n位序列,可以组成n!个数字,那么所谓的序列大就是新序列的数值大小比旧的序列大,并且是所有满足条件中的数值中最小的那一个。

所以要满足两个条件:1.新序列要比旧的序列大;2.新序列要是所有可行序列中最小的一个。

想到自己以前枚举由小到大的序列时,一般思路为先确定高位,然后逐步替换低位。但是在这里程序实现的时候不太可行。为了保证最小这个条件,肯定是从vector的后面朝前考虑。设置两个指针p、q,分别指向前后两个相邻数字,如果前面数字小于后面数字,就考虑数字调换问题。调换的策略是,再从尾端开始,找到一个数字大于p指向的数字,调换。最后再将调换数字后p位置以后的地位数字重新升序排列即可。

下面是实现部分

class Solution {public:    void nextPermutation(vector<int>& nums) {        int length = nums.size();        int post = length - 1;        int pre = 0;        for(; post>=1; post--)        {            if(nums[post-1] < nums[post])                break;        }        if(post == 0)        {            //如果已经是最大序列,则将序列重新升序排列            sort(nums.begin(),nums.end());        }        else        {            //将post-1位置上的数值与后面中大于该位置上的数值交换            pre = post - 1;            post = length - 1;            for(; post > pre; post--)            {                if(nums[post] > nums[pre])                {                    //交换两个数字                    int temp = nums[pre];                    nums[pre] = nums[post];                    nums[post] = temp;                    break;                }            }            //将p之后的序列重新排序            sort(nums.begin()+pre+1, nums.end());        }            }};


0 0
原创粉丝点击