码迷,mamicode.com
首页 > 其他好文 > 详细

Next Permutation

时间:2019-05-07 21:19:49      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:must   public   ble   size   ssi   http   number   space   数字   

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 and use only constant 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,31,3,2
3,2,11,2,3
1,1,51,5,1

code

  一个数组的升序排序后的顺序是所有排列中最小的一个序列,要找到他的下一个较大的序列要从数组最后找到第一个非逆序的数字。

  1. 找出第一个非逆序的数字
  2. 在逆序序列中找出第一个大于非逆序的数字
  3. 翻转第一个大于非逆序的数字到数组的结尾之间的数字
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class Solution
{
public:
    void nextPermutation(vector<int>& nums)
    {
        if(nums.size()<2)
            return ;

        auto cur=nums.end()-1;
        auto pre=cur-1;
        while(pre>=nums.begin()&&*pre>=*cur)
        {
            --cur;
            --pre;
        }
        if(pre<nums.begin())
        {
            reverse(nums.begin(),nums.end());
            return;
        }

        for(cur=nums.end()-1;cur>pre&&*cur<=*pre;--cur);
        swap(*cur,*pre);
        reverse(pre+1,nums.end());
        return ;
    }
};

int main()
{
    vector<int> arr{1,5,1};
    //2 1 3
    Solution s;
    s.nextPermutation(arr);

    for(auto i:arr)
        cout<<i<<" ";

    return 0;
}

 

Next Permutation

标签:must   public   ble   size   ssi   http   number   space   数字   

原文地址:https://www.cnblogs.com/tianzeng/p/10828095.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!