[leetcode]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,31,3,2
3,2,11,2,3

1,1,51,5,1


基本思路:

本题要求当前排列的下一个排列,如果已经是最大的排列,则对排列进行重新排序,返回最小排列。

此题主要的方法是找规律:如何才能得到下一个排列?下一个排列有两个特征(暂未考虑已经是最大的排列的情况)

  1. 下个排列比当前排列要大。
  2. 下个排列是所有比当前排列大的中最小的那个

要实现这个有三个步骤:

  1. 我们要找增大哪一位才能使排列增大。
  2. 这一位增大到多少才能使增大的最少。
  3. 其他低位的排列怎么处理。

从低位依次比较A[i-1]与A[i],找到第一个A[i-1] <A[i] 交换A[i-1] 与其后大于A[i-1]的某位可以实现排列的增大。

在A[i-1]之后的低位找到比A[i-1]大的最小的A[j],交换A[i-1]和A[j].

交换了A[i-1]和A[j],就保证了排列会增大。对于A[i-1]后面的内容,进行从小到大排序就可以了。


代码:

void nextPermutation(vector<int> &num) {  //C++
        for(int i = num.size()-1; i > 0 ; i-- )
        {
                if(num[i] > num[i-1])
                {
                    int min = num[i] - num[i-1];
                    int pos = i;
                    for(int k = i+1; k <num.size(); k++)
                    {
                        if(num[k] - num[i-1] < min && num[k] - num[i-1] >0)
                        {
                            min = num[k] - num[i-1];
                            pos  = k;
                        }
                    }
                    int tmp = num[pos];
                    num[pos] = num[i-1];
                    num[i-1] = tmp;
                    sort(num.begin()+i,num.end());
                    return;
                }
        }
        
        sort(num.begin(),num.end());
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值