您的位置:首页 > 其它

[LeetCode]Next Permutation

2015-08-08 21:57 351 查看

题目

Number: 31

Difficulty: Medium

Tags: Array

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.

[code]1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1


题解

寻找一个排列的下一个排列。下一个排列是指比原排列大的最小一个排列。

如果不存在,那么返回排列的逆序。

解题思路:

从后向前,寻找第一个非升序的数字,比如
4, 5, 8, 6, 3, 1
,找到5

5后面的序列中,从后向前寻找第一个比5大的数字,找到6

交换56,即
4, 6, 8, 5, 3, 1


6后面的序列逆序,即
4, 6, 1, 3, 5, 8


代码

[code]void nextPermutation(vector<int>& nums) {
    int n = nums.size() - 1;
    while(n > 0 && nums[n-1] >= nums
)
        n--;
    if(!n)
    {
        reverse(nums.begin(), nums.end());
        return;
    }
    int change = n - 1;
    n = nums.size() - 1;
    while(n > change && nums[change] >= nums
)
        n--;

    swap(nums
, nums[change]);
    reverse(nums.begin() + change + 1, nums.end());
}


总结

看到一个答案,重复利用STL标准库。

[code]void nextPermutation(vector<int>& nums) {
    auto i = is_sorted_until(nums.rbegin(), nums.rend());
    if(i != nums.rend())
        swap(*i, *upper_bound(nums.rbegin(), i, *i));
    reverse(nums.rbegin(), i);
}


参考:

1, 4, 11 lines C++
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: