Leetcode题解-31. Next Permutation

Leetcode题解-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, 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. 1 2 3
  2. 1 3 2
  3. 2 1 3
  4. 2 3 1
  5. 3 1 2
  6. 3 2 1

重新排序不可能指的是当前序列为第6种,因此需要重新排序到第一种

思路

下一个字典序是比当前序列更大的序列中最小的序列,所以要考虑将尽可能低的位上的数字变成一个更大的数。
从最低位开始看,找到递增序列(从序列尾往头看)的结尾T,它的后一个数Ai比递增序列结尾T小,这个数Ai就是要进行变换的数。在递增序列中找到比Ai大的数中最小的数Min,将Ai和Min交换,重新按从小到大排序递增序列。倘若递增序列是整个序列,意味着这个序列是所有序列中的最大,从小到大排序整个序列。

代码

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int l = nums.size();
        if(l == 0) return;

        int index = l - 1;
        //找到递增序列的结尾
        while(index > 0 && nums[index] <= nums[index-1]){
            index--;
        }
        //该序列是字典序中最大的序列
        if(index == 0){
            sort(nums.begin(), nums.end());
            return;
        }

        int changeIndex = index;
        for(int i = l-1; i > index; i--){
            //nums[index-1]是要进行变换的数
            if(nums[i] > nums[index-1]){
                if(nums[i] < change ){
                    changeIndex = i;
                }
            }
        }

        swap(nums[index-1], nums[changeIndex]);
        //递增序列重新从小到大排序
        sort(nums.begin() + index, nums.end());

    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值