leetcode 31. Next Permutation

来源:互联网 发布:淘宝设计 编辑:程序博客网 时间:2024/06/06 01:24

题目:

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


题目的意思是:
123的全排列按字典顺序为:123 132 213 231 312 321
如果输入其中某一个序列,返回它的下一个序列。
如:
输入:213 输出:231
输入:321 输出:123

注意:一个n个数的全排列组合共有n!个。


class Solution {public:    /*    //step1:从右往左找到第一个破坏升序的元素    //step2:从右往左找到第一个大于破坏升序元素的数    //step3:交换这两个元素    //step4:从破坏升序的元素后一个元素到结尾,逆置    */    void nextPermutation(vector<int>& nums) {        int it = nums.size() - 1;        //step1:找到一个破坏升序(<=)的元素。此时元素的索引为i-1        while (it != 0 && nums[it] <= nums[it - 1])            --it;        //如果序列本来就是降序排列,则直接逆置即可        if (it == 0)        {            reverse(nums.begin(), nums.end());            return;        }        //step2:找到第一个大于破坏升序元素的数。        int greater = nums.size() - 1;        while (nums[greater] <= nums[it - 1])        {            --greater;        }        //step3:交换这两个元素        swap(nums[greater], nums[it - 1]);        //step4:从破坏升序的元素后一个元素到结尾,逆置        reverse(nums.begin() + it, nums.end());    }};

测试代码:

#include<iostream>#include<string>#include<vector>#include<algorithm>using namespace std;int main(){    vector<int> res{0,1,2,3,4};    const vector<int> con = { 4,3,2,1,0 };    Solution cy;    static int conut = 1;    for (conut; conut <= 120; conut++)    {        for (auto i : res)            cout << i;        cout << endl;        cy.nextPermutation(res);    }    system("pause");    return 0;}
0 0
原创粉丝点击