LeetCode(31)-Next Permutation

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">问题描述:</span>

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


问题分析:

  题目的意思是:123的全排列按字典顺序为:

    123 132 213 231 312 321

    如果输入其中某一个序列,返回它的下一个序列。如:输入:213 输出:231 ;输入:321 输出:123

    算法思想:举例如下

    输入:1 4 6 5 3 2

    step1:从右往左找到第一个破坏升序(非严格)的元素,此例中为4.记下标为 i

    step2: 依然从右往左,找到第一个大于4的元素,此例中5,交换4和5.

    step3:从i+1到最右端,逆置。6 4 3 2 to 2 3 4 6


问题求解一:

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        if(!nums.size())
            return;
        
        // find the last wrong number
        int idx = nums.size()-2;
        while(idx >= 0 &&nums[idx] >= nums[idx+1])
            idx--;
        
        // swap the number
        if(idx >= 0){
            int i = idx + 1;
            while(i < nums.size() && nums[i] > nums[idx])
                i++;
            swap(nums[i-1], nums[idx]);
        }
        
        // reverse
        reverse(nums.begin() + idx + 1, nums.end());
    }
};


问题求解二:

使用C++ STL标准库函数next_permutation()

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值