LeetCode-31. Next Permutation

Description

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,31,3,2
3,2,11,2,3
1,1,51,5,1

Solution 1(C++)

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

Solution 2(C++)

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

Solution 3(C++)

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int len=nums.size()-1;
        int left=len, right=len;
        while(nums[left]<=nums[left-1] && left>0) left--;
        if(left==0) {reverse(nums.begin(), nums.end()); return;}
        while(nums[right]<=nums[left-1] && right>0) right--;
        swap(nums[left-1], nums[right]);
        reverse(nums.begin()+left, nums.end());
    }
};

算法分析

解法二我就不多说了,居然有直接的函数。主要说一下解法三。

这一道题的模型其实是,一堆元素构成的数列,元素不同的排列,元素构成的数列对应的数大小也会发生改变。我们先就来研究一下这个规律。

  • 一组元素,按照不递减的顺序从前往后排列,从后往前看就是不递增,那么组成的数最小;
  • 一组元素,按照不递增的顺序从前往后排列,从后往前看就是不递减,那么组成的数最大。

这是第一个规律,很简单。例如:

[1,2,3,4,5,6]
[6,5,4,3,2,1]

那么现在在[6,5,4,3,2,1]这一组元素的左边,新加一个元素:3,那么新构成的数列能组成的最接近当前数列的数:3654321的数列是多少呢?

[4,1,2,3,3,5,6]

因为3作为最高位,比他低的位上的数字构成的数已经是最大的了,要想比他更大,只能改变最高位。而又不能大太多,只能大一点,那么最高位只能换成4,然后除掉4以外,余下元素应该组成最小的数,满足从前往后不递减顺序排列。

以上过程,就足以解决这道题目了。可以参考:LeetCode-31. Next Permutation-Approach #2 Single Pass Approach [Accepted]中的动态图解释。很形象。

这道题对理解这种数列元素排序组成的数很有帮助。

程序分析

略。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值