LeetCode:Next Permutation

本文介绍如何使用C++实现求解下一个字典序排列的算法。通过寻找特定元素进行交换及反转操作,实现在原数组上获得下一个较大排列的目标。同时介绍了当无法找到更大排列时的处理方法。

题目链接

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


步骤如下:

  • 从最尾端开始往前寻找两个相邻的元素,两者满足i < ii(令第一个元素为i,第二个元素为ii)
  • 如果没有找到这样的一对元素则,表明当前的排列是最大的,没有下一个大的排列
  • 如果找到,再从末尾开始找出第一个大于i的元素,记为j                                  本文地址
  • 交换元素i, j,再将ii后面的所有元素颠倒排列(包括ii)
  • 如果某个排列没有比他大的下一个排列(即该排列是递减有序的),调用这个函数还是会把原排列翻转,即得到最小的排列
class Solution {
public:
    void nextPermutation(vector<int> &num) {
        int n = num.size();
        if(n == 1)return;
        for(int i = n-2, ii = n-1; i >= 0; i--,ii--)
            if(num[i] < num[ii])
            {
                int j = n-1;
                while(num[j] <= num[i])j--;//从尾部找到第一个比num[i]大的数,一定可以找到
                swap(num[i], num[j]);
                reverse(num.begin()+ii, num.end());
                return;
            }
        reverse(num.begin(), num.end());
    }
};

 

STL中还提供了一个prev_permutation,可以参考我的另一篇博客:here

 

【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3770126.html

转载于:https://www.cnblogs.com/TenosDoIt/p/3770126.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值