81-Next Permutation

来源:互联网 发布:淘宝联盟怎么提现 编辑:程序博客网 时间:2024/05/17 22:55

-31. Next Permutation My Submissions QuestionEditorial Solution
Total Accepted: 66747 Total Submissions: 250247 Difficulty: Medium
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

求全排列某序列的下一序列

本题难度中等 ,还是有一定难度的:

算法思路:
个例:
1 5 3 4 => 1 5 4 3
1 4 6 5 3 2 => 1 5 2 3 4 6
我们的思路是:

1.从右往左扫描严格下降的序列,直到元素位置pivot不满足,比如上述例1的3和例2的4
2.从右往左扫描第一个大于pivot位置的数,记为bigger(仅大一点)如例2中的5
3.交换bigger与pivot
4.将(pivot+1,end)位置的值取反(这样从降序变成升序)

将例2来做一次实验
1 4 6 5 3 2
1 4 6 5 3 2
=> 1 5 6 4 3 2
=>1 5 2 3 4 6(bingo)

时间复杂度:O(n)

class Solution {public:    void nextPermutation(vector<int>& nums) {        const auto rbeg = nums.rbegin();        const auto rend = nums.rend();        auto pivot = next(rbeg);        while(pivot!=rend && *pivot>=*prev(pivot))++pivot;        if(pivot==rend){            reverse(rbeg,rend);            return;        }        auto bigger = find_if(rbeg,pivot,bind1st(less<int>(),*pivot));        swap(*pivot,*bigger);        reverse(rbeg,pivot);    }};
0 0