Next Permutation

本文介绍了一个算法,用于在原地将一组数字重新排列成字典序中下一个更大的排列。若无法生成更大的排列,则将其重新排列为最小可能的顺序(即升序)。文章详细解释了实现步骤,并提供了一个C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


这道题如果明白啥叫lexicographically就算会做了。。。坑爹的题目。。。STL居然有这么个algorithm叫find_nextPermutation....

1. 从后往前扫,找到第一个左面小于右面的,i

2. 从后扫到 i-1, 包括 i, 找第一个大于i的j, 否则找不到的话也要进行第三步

3. 交换 i,j数

4. 因为 descending是最大,那么ascending就是最小, 那么reverse一下

5. 如果一直没找到,直接reverse.

class Solution {
public:
    void nextPermutation(vector<int> &num) {
        int len=num.size(); 
        for (int i=len-2; i>=0;i--){
            // find the last ascending pair
            if (num[i+1]>num[i]){
                int j;
                for (j=len-1;j>i-1;j--)
                    if (num[j]>num[i])
                        break;
                // include j=i;
                swap(num[i],num[j]);
                reverse(num.begin()+i+1,num.end());
                return;
            }
        }
        reverse(num.begin(),num.end());
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值