LeetCode *** 31. Next Permutation

来源:互联网 发布:厦门众途软件 编辑:程序博客网 时间:2024/05/17 22:30

题目:

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


分析:

最近好自恋 - -,,,


代码:

class Solution {public:    void nextPermutation(vector<int>& nums) {        int pos=nums.size()-1;        while(pos>0){            if(nums[pos]>nums[pos-1])break;            --pos;        }        if(pos==0)sort(nums.begin(),nums.end());        else {            int minp=INT_MAX,rec=pos;            for(int i=pos;i<nums.size();++i){                int tmp=nums[i]-nums[pos-1];                if(tmp>0&&tmp<minp){                    rec=i;                    minp=tmp;                }            }            int tmp=nums[pos-1];            nums[pos-1]=nums[rec];            nums[rec]=tmp;            sort(nums.begin()+pos,nums.end());        }    }};


0 0
原创粉丝点击