leetCode | Next Permutation

本文介绍了一个经典的STL算法——下一个排列。该算法用于重新排列数组中的数字,使其成为字典序中比当前序列更大的序列。如果无法实现,则将序列重新排列为最小可能的顺序(即升序)。本文详细解释了算法的实现过程,并提供了具体的代码实现。

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

题目:

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


思路:

STL中的经典算法。

函数实现原理如下:

在当前序列中,从尾端往前寻找两个相邻元素,前一个记为*i,后一个记为*ii,并且满足*i < *ii。然后再从尾端寻找另一个元素*j,如果满足*i < *j,即将第i个元素与第j个元素对调,并将第ii个元素之后(包括ii)的所有元素颠倒排序,即求出下一个序列了。



代码:

class Solution {
public:
    void nextPermutation(vector<int> &num) {
        if(num.size()>1)
        {
            int i=num.size()-1;
            for(;i>=1;i--)
            {
                if(num[i-1]<num[i])
                {
                    break;
                }
            }
            if(i==0)
            {
                for(int k=0;k<num.size()/2;k++)
                {
                    swap(num, k, num.size()-1-k);
                }
            }
            else
            {
                int ii = i;
                i -= 1;
                int j=num.size()-1;
                for(;j>=0;j--)
                {
                    if(num[i]<num[j])
                    {
                        break;
                    }
                }
                swap(num,i,j);
                for(int k=0;k<(num.size()-ii)/2;k++)
                {
                    swap(num, ii+k, num.size()-1-k);
                }
            }
        }
    }
    
    void swap(vector<int> &num, int i, int j)
    {
        int t = num[i];
        num[i] = num[j];
        num[j] = t;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值