LC31. 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


LeetCode里面有很多关于Permutation的题目,在这个系列当中有和回溯挂钩的求所有Permutation的题目,分为包含重复和不包含重复的两种,之前已经写过关于这两题的总结。这道题和LC 60 Permutation Sequence更像,相比那道题,这道求Next Permutation的题目要更简单一点。

思路是这样,从给定的数组最右侧向左侧遍历,寻找一个number and its index where the ascending sequence is interrupted. 例如给一个数组 [6, 5, 1, 4, 3, 2],从最右侧的 2 开始向前看,直到找到打断上升的那个数字,这里就是 num[2] = 1。 观察从它开始的子串,即 [1, 4, 3, 2],第一个数往后的所有数(4,3,2)都是有序的递减的,而递减的子串已经是所有permutation当中的最后一个,所以这时必须从递减的里面找出一个最小的数放在原来 1 的位置上,这样就变成了[2, 4, 3, 1]。还没有结束,此时开始了一个新的排序,2的位置就是它在next permutation中应该在的位置,但是作为新的permutation的开始,它后面的数组应该变成有序递增。代码:

void nextPermutation(vector<int>& nums) {
    int i, j;
    i = j = (int)nums.size() - 1;
    // iterate from right to left, see where breaks the ascending order.
    while (i > 0 && nums[i-1] >= nums[i]) {
        i--;
    }
    if (i == 0) {
        // already the biggest permuatation, no next exists. arrange it to ascending order.
        sort(nums.begin(), nums.end());
        return;
    }
    i--;
    while (i < j && nums[j] <= nums[i]) {
        j--;
    }
    // on right side of nums[i] exists smallest nums[j] but bigger than nums[i].
    swap(nums[i], nums[j]);
    // nums on right side of nums[i] just need to be sorted by ascending order.
    sort(nums.begin() + i + 1, nums.end());
}
需要注意的是,当数组已经是整个递减的情况,说明已经不存在有效的next permutation,因此需要特别处理,即sort()。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值