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

解题思路:输出字典序中的下一个排列。比如123生成的全排列是:123,132,213,231,312,321。那么321的next permutation是123。下面这种算法据说是STL中的经典算法。在当前序列中,从尾端往前寻找两个相邻升序元素,升序元素对中的前一个标记为k - 1。然后再从尾端寻找另一个大于k - 1的元素,并与k - 1指向的元素交换,然后从第k个元素之后(包括k)逆序排列。比如14532,那么升序对为45,k - 1指向4,由于k - 1之后除了5没有比4大的数,所以45交换为54,即15432,然后将从k之后的元素逆序排列,即432排列为234,则最后输出的next permutation为15234。

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int n = nums.size();
        if(n == 1 || n == 0)
            return;
        int k = n - 1;
        //找到从右到左第一个升序的坐标k - 1
        while(k > 0){
            if(nums[k] > nums[k - 1]){
                break;
            }
            k--;
        }
        int t = n - 1;
        //找到从右到左第一个大于k - 1坐标的值并交换 除非k == 0
        while(t >= k && k != 0){
            if(nums[t] > nums[k - 1]){
                int temp = nums[t];
                nums[t] = nums[k - 1];
                nums[k - 1] = temp;
                break;  
            }
            t--;
        }
        //从k开始取逆序
        int m = n - 1;
        while(k < m){
            int temp = nums[m];
            nums[m] = nums[k];
            nums[k] = temp;
            k++;
            m--;
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值