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 3 5 4 2,索引i=2,然后从i向右遍历,找到索引j,满足: 索引j+1所对应的值小于i对应的值。即j=4,将i与j的值对调,然后将i+1...n的数值互调。代码如下:

class Solution {
public:
    void swap(int &a, int &b) {
        a ^= b;
        b ^= a;
        a ^= b;
    }
    void nextPermutation(vector<int> &num) {
        if (num.empty() || num.size() == 1) {
            return;
        }
        vector<int> res;
        res.clear();
        int len = num.size();
        res.resize(len);
        int i,j;
        for(i=len-2; i>=0; i--) {
            if(num[i] < num[i+1]) {
                break;
            }
        }
        if(i < 0) {
            for(j=0; j<len; ++j) {
                res[j] = num[len-j-1]; 
            }
            num = res;
        }
        else {
            for(j=i+1; j<len; ++j) {
                if(num[j] <= num[i]) {
                    break;
                }
            }
            j = (j == len ? len-1 : j-1);
            swap(num[i],num[j]);
            int L,R;
            for(L=i+1,R=len-1; L<R; ++L,--R) {
                swap(num[L],num[R]);
            }
        }
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值