【LeetCode】31. Next Permutation (2 solutions)

本文详细介绍了NextPermutation算法的实现方法,通过三种不同的情况讨论如何寻找并生成字典序下一个更大的排列。针对不同输入,文章提供了清晰的步骤说明及代码实现。

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

 

解法一:just a joke :)

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

 

解法二:

1、如果数组为降序,则根据题意,升序排序后返回。

2、如果数组为升序,则交换最后两个元素后返回。

3、举例来说明:

[1,2,5,4,3]-->[1,3,2,4,5]

从右往左递增的序列是不改动的。因为递增已经是最大。

因此要改动的就是递增部分的断点。

如上例,5,4,3是不可能改动的,越改越小,与“下一个序列”的定义不符。

因此要改动的就是2.

需要将2的位置替换为3,也就是从右往左比2大的数中最小的那个数,也就是3。如果不是选最小,那就会跳过很多排列。

将3放到2的位置,新排列的头部为[1,3]。

由于3第一次出现在第二个位置,因此其余数组应该呈最小序,也就是将[5,4,2]排序。

最终结果为[1,3,2,4,5]

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        if(nums.empty())
            return;
        int size = nums.size();
        int ind = size-1;
        while(ind > 0 && nums[ind] <= nums[ind-1])
            ind --;
        if(ind == 0)
        {// descend
            sort(nums.begin(), nums.end());
        }
        else if(ind == size-1)
        {// ascend
            // swap the last two element
            swap(nums[ind], nums[ind-1]);
        }
        else
        {
            int ind2 = size-1;
            while(nums[ind-1] >= nums[ind2])
                ind2 --;
            // nums[ind-1] < nums[ind2]
            swap(nums[ind-1], nums[ind2]);
            sort(nums.begin()+ind, nums.end());
        }
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值