Next Permutation

来源:互联网 发布:日版手机网络锁 编辑:程序博客网 时间:2024/06/01 20:24

题目名称
Next Permutation—这里写链接内容

描述
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,23,2,1 → 1,2,31,1,5 → 1,5,1

分析
  参照我之前写的那篇字典序—lexicographical order,里面的思路就是本题的结果方法。

C++代码

class Solution {public:    void nextPermutation(vector<int>& nums) {        int size = nums.size();        if(size==0 || size==1)            return;        vector<int>::iterator p = nums.end()-1,q=nums.end()-1;        while( p!=nums.begin() && *p<=*(p-1) )            p--;        if(p==nums.begin())            reverse(nums.begin(),nums.end());        else if(p==nums.end()-1)            swap(*p,*(p-1));        else{            p--;            while(*q<=*p)                q--;            swap(*p,*q);            reverse(p+1,nums.end());        }    }};

总结
  多学点计算机相关的知识,你要记住,你每多学一点技能,就会少一次求别人,就会多一项赚钱手段。

0 0
原创粉丝点击