LintCode 52: Next Permutation

  1. Next Permutation
    中文English
    Given a list of integers, which denote a permutation.

Find the next permutation in ascending order.

Example
Example 1:

Input:[1]
Output:[1]
Example 2:

Input:[1,3,2,3]
Output:[1,3,3,2]
Example 3:

Input:[4,3,2,1]
Output:[1,2,3,4]
Notice
The list may contains duplicate integers.

解法1:
思路:以input={1,1,3,2,1}为例,
从后往前看,直到找到一个nums[i]>nums[i-1],index=i。当index=0,则nums为降序排列,此时将nums reverse即可。
这里index = 2 (对应3),然后我们再从后往前看,找到第一个大于nums[index-1]的元素,发现是2,我们将2和nums[1]=1对调,得到{1,2,3,1,1},但这个还不是next permuation。我们再将{3,1,1}反过来,注意此时{3,1,1}一定是降序排列,就得到{1,2,1,1,3}。
为什么{3,1,1}一定是降序排列?因为{3,2,1}一定是降序排列,而2又是第一个大于1的元素。
代码如下:

class Solution {
public:
    /**
     * @param nums: A list of integers
     * @return: A list of integers
     */
    vector<int> nextPermutation(vector<int> &nums) {
        int n = nums.size();
        
        if (n <= 1) return nums;
        
        vector<int> result = nums;
        
        int index = 0;
        for (int i = n - 1; i > 0; --i) {
            if (nums[i] > nums[i - 1]) {
                index = i;
                break;
            }
        }
        
        if (index == 0) {
            reverse(result.begin(), result.end());
            return result;
        }
        
        for (int i = n - 1; i >= index; --i) {
            if (nums[i] > nums[index - 1]) {
                swap(result[i], result[index - 1]);
                reverse(result.begin() + index, result.end());
                return result;
            }
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值