31. Next Permutation

31. Next Permutation

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 and use only constant 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

参考https://blog.csdn.net/cinderella_niu/article/details/42525241

解题思路:

下一个最大的数应该是有尽可能长的相同前缀,剩余的部分应该是这串数字的第一个数小于第二个数,剩下的数字是由大到小排列的,比如68741。改变68741应该是,让这串数字的第一个数字尽可能的小,但是应当大于原来的数字,余下的数字也应当尽可能的小。也即是说找一个大于6的数字,且这个数字是所有大于6的数字中最小的,然后交换6跟这个数字的位置,变成78641,这样就做到了第一个数字尽可能的小,然后将剩下的四个数字按从小到大的顺序排列,就可以得到最小的剩下的那串数字,也就是1468,最后这个要求的数字就是(前缀+71468)

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int cnt = nums.size();
        if(cnt<=1) return;
        int flag = 0;
        for(int i=cnt-1; i>0; i--) {
            if(nums[i-1]<nums[i]) {
                int j = cnt-1;
                while(nums[j]<=nums[i-1]) j--;
                swap(nums[i-1], nums[j]);
                sort(nums.begin()+i, nums.end());
                return;
            }
        }
        reverse(nums.begin(), nums.end());
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值