array--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

问题解析:

1. 此题是给定序列的下一个变化序列问题。最初是递增序列,然后依次从后面开始调换位置。一直到递减序列后,说明到了最后一个序列,则下一个序列就是初始序列,是一个循环。
2. 解决此问题,先需要看清楚变化规律。比如序列:1、2 、4 、5 、3。从最后一个数开始看起,发现最后两个已经逆序,说明以最后两个数为子数组,已经到了最后一个序列。然后继续看最后三个子数组,发现并不完全逆序,说明由最后三个数组成的子数组并没有到最后一个序列。则最后三个数组成的子数组初始序列应该是由小到大:3, 4, 5。现在是4, 5,3。下一个应该是5, 3,4.和前两个数组合就是下一个序列。说一下原因,是4,5, 3中后两个数已经逆序,但是第一个数4小于第二个数5,则不完全逆序,找出,后两个数中,大于4的最小数5,将4和5互换位置,然后将后两个数进行由小到大排序就是下一个序列了。

代码如下:

class Solution {
public:
    void nextPermutation(vector<int>& nums)
    {
        int size = nums.size();
        if(size < 2)
            return;
        
        // 第一遍,开始遍历从后往前找到第一个不是递增的数
        int i = size-2;
        while(size >= 0)
        {
            if(nums[i] < nums[i+1])
                break;
            --i;
        }
        if(i < 0)
        {
            sort(nums.begin(), nums.end());
            return;
        }
        
        // 第二遍遍历,为了找出i后面的数中比i对应数大的最小的那个数
        int j=size-1, min = -1;
        for(; j>i; --j)
        {
            if(nums[j] > nums[i] && (min == -1 ||nums[j]<=nums[min]))
            {
                min = j; 
            }
        }
        
        // 互换位置i和j的对应数位置,并对i后面的所有数进行排序
        if(min != -1)
        {
            int temp = nums[i];
            nums[i]  = nums[min];
            nums[min] = temp;
            sort(nums.begin()+i+1, nums.end());
        }
        
        return;
    }
};




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值