leetcode 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 and use only constant 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

解决思路:
[4,7,6,5,3,1]
对于这样的一个序列我们要求他的下一个排列。

  1.   从最右边开始找([...,i-1,i,i+1,...]排列顺序像这个样子),找到第一个a[i]和a[i-1]使得a[i] > a[i-1];这样a[i]右边的序列就是一个降序的排列(这个序列理论上没有下一个排列,题目中让这种情况的下一个变成了第一个)。在例子中就是a[i-1]=4,a[i]=7.
  2.  从a[i]开始的降序排列中找到刚好大于a[i-1]的数,进行交换,也就是从[7,6,5,3,1]中找到刚好大于4的数(5>4,4>3)不过要判断一下边界情况。将5,4的位置互换,序列结构变成[5,7,6,4,3,1]
  3.   将降序的序列结构反转,就可以得到最终的下一个排列。[5,7,6,4,3,1]变成了[5,1,3,4,6,7]

 

void nextPermutation(vector<int>& nums) {
        /*if (nums.empty() == true)
            return nums;
        if (nums.size() == 1)
            return nums;*/
        int flag = 0;
        for (int i = nums.size()-1 ; i > 0 ; i--)
        {
            if(nums[i] > nums[i-1])
            {
                flag = 1;
                for(int j = i ; j < nums.size() ; j++)
                {
                    if(j == nums.size()-1)
                    {
                        std::swap(nums[i-1],nums[nums.size()-1]);
                        break;
                    }
                    //因为会出现例子3的情况,有可能出现等于
                    if(nums[i-1] < nums[j] && nums[i-1] >= nums[j+1])
                    {
                        //cout<<nums[i-1]<<endl;cout<<nums[j]<<endl;cout<<nums[j+1]<<endl;
                        std::swap(nums[i-1],nums[j]);
                        break;
                    }
                    
                }
                std::reverse(nums.begin()+i,nums.end());
                break;
            }
        }
        if (flag == 0)
        {
            std::reverse(nums.begin(),nums.end());
        }
        
        
    }


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值