Leetcode 31 Next Permutation

来源:互联网 发布:mac dare you 不好看 编辑:程序博客网 时间:2024/06/16 22:01

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

找到字典序的下一个排列.

偷懒做法

class Solution {public:    void nextPermutation(vector<int>& nums) {        if(next_permutation(nums.begin(),nums.end())) return;        sort(nums.begin(),nums.end());    }};

当然本着小题大做的原则,肯定不能这样放松要求哇。

算法原理查看 http://blog.csdn.net/accepthjp/article/details/52432954

找出从最右向左最长递增序列的左边一个元素,将最长递增序列逆置,这样得到的是该序列的最小字典序排列,再将找到的左边一个元素和该序列中大于它的最小一个元素交换位置。

class Solution {public:    void nextPermutation(vector<int>& nums) {        if(nums.size()<2) return ;        for(int i=nums.size()-1;i>0;i--)            if(nums[i]>nums[i-1])            {                reverse(nums.begin()+i,nums.end());                vector<int>::iterator it=upper_bound(nums.begin()+i,nums.end(),nums[i-1]);                swap(*it,nums[i-1]);                return ;            }        reverse(nums.begin(),nums.end());    }};




1 0
原创粉丝点击