leetcode question 31: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


这道题要求我们求给定一列数的下一个全排列,而且是按字典顺序的。比如例子中的123,比123大的最小数是132,比115大的最小数是151,而321已经是最大的了,就输出最小值123。

经过观察,求最小的全排列数的方法如下:

从后往前迭代逐个数字a,值到找到这个数字a后面有比它大的数字b,就调换这两个数字的位置,再对原来数字a的位置后面的所有数字升序排序,得出的结果即为下一个全排列数。

如123,找到3比2大,就将这两个位置互换,再对原来2后面的所有数字进行排序(此处只有一位,不用排),得到结果132。

最后结果代码如下:

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        //nums为空或只有一个数
        if( nums.size() <= 1 ){
            return ;
        }
        
        //判断是否是最大值,即看是否是降序
        for( int i = 0 ; i < nums.size() ; i ++ ){
            if( i > 0 && nums[i] > nums[i-1] ){
                break;
            }else if( i == nums.size() - 1 ){
                sort( nums.begin() , nums.end() );
                return ;
            }
        }
        
        for( int i = nums.size() - 2 ; i >= 0 ; i-- ){
            int flag = 0;
            for( int j = nums.size() - 1 ; j > i ; j -- ){
                if( nums[j] > nums[i] ){
                    int term = nums[j];
                    nums[j] = nums[i];
                    nums[i] = term;
                    sort( nums.begin() + i + 1, nums.end() );
                    flag = 1;
                    break;
                }
            }
            
            if( flag == 1 ){
                break;
            }
        }
        
    }
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值