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,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

» Solve this problem


题目的意思是求字典序中的下一个。

输入:1 2 3

它可以生成:1 2 3, 1 3 2, 2 1 3, 2 3 1, 3 1 2, 3 2 1.

其中1 3 2是1 2 3的下一个,所以输出: 1 3 2


输入:3 2 1

它生成的数字跟1 2 3相同,也是:1 2 3, 1 3 2, 2 1 3, 2 3 1, 3 1 2, 3 2 1.

其中1 2 3是3 2 1的(循环)下一个,所以输出:3 2 1


对任意排列:A[0] A[1] A[2] ... A[i]... A[n]

假设 A[i - 1] < A[i],且有A[i] >= A[i+1] >= A[i + 2] >= ... >= A[n - 1]

从A[i]到A[n - 1]中选取一个最小的数A[k],A[k]满足条件:A[k] > A[i - 1]

则A[0] A[1] A[2] ... A[i]... A[n]的下一个排列为

A[0] A[1] A[2] ... A[k] A[n - 1] A[n - 2] ... A[k + 1] A[i - 1] A[k - 1] ... A[i]。


例子更能说明:

假设输入为  5 5 2 4 7 6 3

从后往前观察,对于A[5] = 6 >= A[6] = 3。(交换A[5]和A[6]得到的排列: 5 5 2 4 7 3 6 小于原排列,这一步是没有必要做的,只是为了让大家看清楚)

A[4] = 7 >= A[5] >= A[6]。(交换A[4]和A[5]或者A[4]和A[6]等,得到的都比原排列小)

A[3] = 4 < A[4] >= A[5] >= A[6],这时从7 6 3中选择6,6是这三个数中大于4的最小的数,交换A[3] = 4和A[5] = 6,得到: 5 5 2 6 7 4 3

明显5 5 2 6 7 4 3比原排列大,但不是原排列的next permutation。

需要调整7 4 3得到最小的3 4 7,最终就是输出5 5 2 4 3 6 7


对于输入3 2 1

找不到任何一个A[i - 1] < A[i],所以输出为它的(循环)下一个: 1 2 3


class Solution {
public:
    void nextPermutation(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function        
        int i = num.size() - 2;
        while (i >= 0 && num[i] >= num[i + 1]) {
            i--;
        }
        if (i < 0) {
            reverse(num.begin(), num.end() - 1);
        }
        else {
            int j = i + 2;
            while (j < num.size() && num[j] > num[i]) {
                j++;
            }
            j--;
            
            num[i] ^= num[j];
            num[j] ^= num[i];
            num[i] ^= num[j];
            
            reverse(num.begin() + i + 1, num.end() - 1);
        }
    }

private:
    void reverse(vector<int>::iterator i1, vector<int>::iterator i2) {
        while (i1 < i2) {
            *i1 ^= *i2;
            *i2 ^= *i1;
            *i1 ^= *i2;
            
            i1++;
            i2--;
        }
    }
};


评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值