首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Leetcode 31 Next Permutation

Leetcode 31 Next Permutation

作者头像
triplebee
发布2018-01-12 15:08:41
发布2018-01-12 15:08:41
7210
举报

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

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

偷懒做法

代码语言:javascript
复制
class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        if(next_permutation(nums.begin(),nums.end())) return;
        sort(nums.begin(),nums.end());
    }
};

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

算法原理查看 https://cloud.tencent.com/developer/article/1019302

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

代码语言:javascript
复制
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());
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016-09-04 ,如有侵权请联系 cloudcommunity@tencent.com 删除
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档