Next Permutation

来源:互联网 发布:软考初级程序员答案 编辑:程序博客网 时间:2024/06/07 15:50
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.从后往前,找到第一个 A[i-1] < A[i]的,可以发现A[i]到A[n-1]这些都是单调递减序列。
2.从 A[n-1]到A[i]中找到一个比A[i-1]大的值(也就是说在A[n-1]到A[i]的值中找到比A[i-1]大的集合中的最小的一个值)
3.交换 这两个值,并且把A[n-1]到A[i]排序,从小到大。

class Solution {public:    void nextPermutation(vector<int>& nums) {        if(nums.empty())        return ;    int len=nums.size()-1;    while(len>0&&nums[len]<=nums[len-1])        len--;    if(len==0)    {        sort(nums.begin(),nums.end());        return;    }    else if(len==nums.size()-1)    {        swap(nums[len],nums[len-1]);        return;    }    else    {        int len2=nums.size()-1;        while(nums[len-1]>=nums[len2])            len2--;        swap(nums[len2],nums[len-1]);        sort(nums.begin()+len,nums.end());
    }    }};
可以将上述sort的地方换成reverse。

class Solution {public:    void nextPermutation(vector<int>& nums) {        if(nums.empty())        return ;    int len=nums.size()-1;    while(len>0&&nums[len]<=nums[len-1])        len--;    if(len==0)    {        reverse(nums.begin(),nums.end());        return;    }    else if(len==nums.size()-1)    {        swap(nums[len],nums[len-1]);        return;    }    else    {        int len2=nums.size()-1;        while(nums[len-1]>=nums[len2])            len2--;        swap(nums[len2],nums[len-1]);        reverse(nums.begin()+len,nums.end());    }    }};



0 0
原创粉丝点击