LeetCode31. Next Permutation

来源:互联网 发布:非诚勿扰网络直播时间 编辑:程序博客网 时间:2024/06/04 21: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

#include<vector>#include<iostream>using namespace std;class Solution {private:     void myinverse(vector<int>& nums,int left,int n){        int sum=n+left,j=(sum+1)/2,temp,i=left;        while(i<j){            temp=nums[i];            nums[i]=nums[sum-1-i];            nums[sum-1-i]=temp;             ++i;        }               }public:    void nextPermutation(vector<int>& nums) {        int n=nums.size();        if(n>1){            int i=n-1,j=n-2,temp=0;            if(nums[i]>nums[j]){                temp=nums[i];                nums[i]=nums[j];                nums[j]=temp;            }            else{                while(i>0){                    if(nums[i]>nums[i-1]){                                              break;                    }                    --i;                }                if(i==0){                    myinverse(nums,0,n);                }                else if(nums[i-1]<nums[n-1]){                    temp=nums[i-1];                    nums[i-1]=nums[n-1];                    nums[n-1]=temp;                     myinverse(nums,i,n);                }                else if(nums[i-1]>=nums[n-1]){                    temp=nums[i-1];                    int t=i;                    while(temp<nums[t]){                                                ++t;                                        }                    --t;                    nums[i-1]=nums[t];                    nums[t]=temp;                    nums[t]=temp;                    myinverse(nums,i,n);                                }            }        }    }};void main(){    //int a[6]={5,4,7,5,3,2},n=6;    int a[6]={4,4,2,3,1,1},n=6;    //int a[6]={1,3,6,5,4,2},n=6;    //int a[2]={1,1},n=2;    vector<int> nums(n);    nums.reserve(n);    nums.assign(&a[0],&a[n]);    cout<<nums[0]<<endl;    cout<<nums[1]<<endl;    cout<<nums[2]<<endl;    cout<<nums[3]<<endl;    cout<<nums[4]<<endl;    cout<<nums[5]<<endl;    Solution So;    So.nextPermutation(nums);    cout<<nums[0]<<endl;    cout<<nums[1]<<endl;    cout<<nums[2]<<endl;    cout<<nums[3]<<endl;    cout<<nums[4]<<endl;    cout<<nums[5]<<endl;}

这里写图片描述

0 0
原创粉丝点击