leetcode:31. Next Permutation 下一个排列

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

思路
  • 这是一道全排列的题,思路可参考31 Next Permutation
  • 如果不熟悉原理,非常容易绕晕
  • 采用从尾部往前遍历的方式
  • 关键是从后往前遍历,找到破坏升序排列的位置,然后交换位置后,对后面的数据进行重新排序。
算法步骤

输入: 一个排列nums
输出:下一个排列
1. 判断nums是否为空,为空则返回
2. 设nums的长度为m。外循环从倒数第2个开始往前遍历:i
1. 内循环从倒数第1个开始往前遍历,直到i+1:j
1. 如果i+1到m的数中有大于第i个数,则在满足该条件的数集中找到最小的值min,并记录位置为k。
2. 如果位置k存在,则交换第i个数和第k个数,并且对i+1到m个数进行升序排列
3. 返回下一个排列nums。

代码
bool Solution::nextPermutation2(vector<int>& nums)
{
    if(nums.size()==0)
        return false;
    for(int i=nums.size()-2;i>=0;i--)
    {
        int min=INT_MAX;
        int k=-1;
        for(int j=nums.size()-1;j>i;j--)
        {
            if(nums[i]<nums[j] && nums[j]< min)
            {
                k=j;
                min=nums[j];
            }
        }
        if(k != -1)
        {
            int temp=nums[k];
            nums[k]=nums[i];
            nums[i]=temp;
            sort(nums.begin()+i+1,nums.end());
            return false;
        }
    }
    // 如果是最大时
    for(int i=0;i<nums.size()/2;i++)
    {
        int temp=nums[i];
        nums[i]=nums[nums.size()-i-1];
        nums[nums.size()-i-1]=temp;
    }
    return true;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值