Leetcode 31. Next Permutation

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,31,3,2
3,2,11,2,3
1,1,51,5,1

Solution

只有一种解法了。

我们先列出一组字典序的排列,然后找找规律

1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 1 3
2 4 3 1
......

有点难以寻找,但是到了最后,我们可以总结出来这样一个规律,可以直接找到下一个字典序。

我们以1 4 3 2为例子说明。

(1) 首先,先从后往前遍历,找到第一组顺序的组合。在例子中,我们可以找到1 4。此时我们记录下这队组合中前边那个,也就是1

(2) 然后,我们再次从后往前遍历,在这个数字的后边寻找比上一步中找到的那个数字大的最小的数。在这个例子中,我们进行比较,21大,341大但是比同样也比2大,因此,我们取2作为这一步寻找的结果。

(3) 现在,我们交换21。得到2 4 3 1

(4) 然后,把较前那个数字之后的所有部分进行逆序。即将4 3 1进行逆序。这样我们就得到了下一个字典序。

代码如下:

void nextPermutation(vector<int>& nums) {
        // (1)
        int i = -1;
        for (i = nums.size() - 1; i > 0; i--) {
            if (nums[i-1] < nums[i]) {
                break;
            }
        }
        i--;
        if (i == -1) {
            std::sort(nums.begin(), nums.end());
            return;
        }
        // (2)
        int min_greater_i = nums.size() - 1, min_greater = INT_MAX;
        for (int j = nums.size() - 1; j > i; j--) {
            if (nums[j] > nums[i] && nums[j] < min_greater) {
                min_greater_i = j;
                min_greater = nums[j];
            }
        }
        // (3)
        swap(nums[i], nums[min_greater_i]);   
        // (4)     
        reverse(nums.begin() + i + 1, nums.end());
        return;
    }

代码注释中的(1)、(2)、(3)、(4)等和解法中的标记相对应。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值