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

先解释一下题目的意思。数组中的数字组合起来可以得到一个整数,我们要对数组进行性重新排列,使里面的数字排列得到仅仅比当前数字大的数字组合。如果当前数字就是最大的组合,那就输出最小的组合。
这道题的思路比较简单。只要明确满足nums[c]>nums[c-1]的条件就是需要交换的位置就可以了。之后要把后续的数组按升序排序,找到第一个比nums[c-1]大的数字并与之交换即可。

class Solution {
public:
    void nextPermutation(vector<int>& nums) {

        int c=nums.size()-1;   //确定交换位置
        bool flag=false;   //判断所有数字是否都相同
        for(c;c>0;c--){
            if(nums[c]!=nums[c-1])
                flag=true;
            if(nums[c]>nums[c-1]){   //当前数字比前一个大的时候就是需要交换的地方
                break;
            }
        }
        if(c>0){   //存在需要交换的地方
            for(int i=c;i<nums.size()-1;i++){  //对后续的数组进行升序排序
                for(int j=i+1;j<nums.size();j++){
                    if(nums[i]>nums[j]){
                        int tmp=nums[i];
                        nums[i]=nums[j];
                        nums[j]=tmp;
                    }
                }
            }
            for(int j=c;j<nums.size();j++){  //找到比c-1大的第一个数,并交换
                if(nums[j]>nums[c-1]){
                    int tmp=nums[j];
                    nums[j]=nums[c-1];
                    nums[c-1]=tmp;
                    break;
                }
            }
        }
        if(c==0 && flag){  //不存在交换条件,且数组里数字不同时,对数组进行排序
            int l=0,r=nums.size()-1;
            while(l<r){
                int swap=nums[l];
                nums[l]=nums[r];
                nums[r]=swap;
                l++;
                r--;
            }
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值