lintcode:Next Permutation

Given a list of integers, which denote a permutation.

Find the next permutation in ascending order.

Example For [1,3,2,3], the next permutation is [1,3,3,2]

For [4,3,2,1], the next permutation is [1,2,3,4]

Note The list may contains duplicate integers.

方法一

class Solution {
public:
    /**
     * @param nums: An array of integers
     * @return: An array of integers that's next permuation
     */
    vector<int> nextPermutation(vector<int> &nums) {
        // write your code here
        next_permutation(nums.begin(),nums.end());
        return nums;
    }
};

next_permutation()函数包含在头文件algorithm中。

方法二

弄清楚求下一个排列的原理
这里写图片描述

这张图说明了方法。
为什么这样呢?其实也很容易理解。
1.比如说上面的例子,6的右边8,7,4,3,2已经是它们自己的最大排列。
2.要想求6,8,7,4,3,2的下一个排列肯定是在右边找一个比6大最小数的替换6,那么就是7了。
3.交换6,7之后,7右边的排列还是最大排列,逆序之后得到其最小排列,这样就能得到整个的下一个排列。

class Solution {
public:
    /**
     * @param nums: An array of integers
     * @return: An array of integers that's next permuation
     */
    vector<int> nextPermutation(vector<int> &nums) {
        // write your code here
        int len=nums.size();

        if(len==1){
            return nums;
        }

        int partition_index;
        int i=len-1;
        while(i){
            if(nums[i-1]<nums[i]){
                partition_index=i-1;
                break;
            }
            i--;
        }


        if(i==0){
            reverse(nums.begin(),nums.end());
            return nums;
        }

        int change_index;
        for(int i=len-1;i>partition_index;i--){
            if(nums[i]>nums[partition_index]){
                change_index=i;
                break;//
            }
        }

        swap(nums[partition_index],nums[change_index]);

        reverse(nums.begin()+partition_index+1,nums.end());

        return nums;
    }
};
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值