31. Next Permutation

来源:互联网 发布:网络语右友是什么意思 编辑:程序博客网 时间:2024/05/20 20:03

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
算法思想:
对当前排列从后向前扫描,找到一对为升序的相邻元素,记为i和j(i < j)。如果不存在这样一对为升序的相邻元素,则序列逆序排列,直接逆转序列,算法结束;否则,重新对当前排列从后向前扫描,找到第一个大于i的元素k,交换i和k,然后对从j开始到结束的子序列反转,则此时得到的新排列就为下一个字典序排列。

#include<iostream>#include<algorithm>#include<vector>using namespace std;class Solution {public:    void nextPermutation(vector<int>& nums) {        if(nums.size()<2)            return;        int i;        for(i=nums.size()-1;i>0;i--)        {            if(nums[i]>nums[i-1])//找到一对升序排列的数                break;        }        if(i==0)//逆序排列直接逆转            reverse(nums.begin(),nums.end());        else        {            int k;            for(k=nums.size()-1;k>i;k--)//在i到nums.end()中寻找第一次比nums[i-1]大的数nums[k]            {                if(nums[k]>nums[i-1])                    break;            }            swap(nums[i-1],nums[k]);//交换两个数            reverse(nums.begin()+i,nums.end());        }        return;    }};int main(){    vector<int>number;    int i,N,temp;    cin>>N;    for(i=0;i<N;i++)    {        cin>>temp;        number.push_back(temp);    }    Solution solve;    solve.nextPermutation(number);    for(i=0;i<number.size();i++)        cout<<number[i]<<' ';    cout<<endl;    return 0;}
0 0