leetcode--31. Next Permutation

本文详细解析了一个经典算法问题——实现下一个排列。通过实例演示了如何在不使用额外内存的情况下,找到给定数字序列的下一个字典序排列。文章还提供了一段C++代码实现,帮助读者理解算法的具体操作步骤。

摘要生成于 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

这篇博客作者讲的比较详细,我是参考的他的:https://yq.aliyun.com/articles/863#

题目大意:

是数学中的排列组合,比如“1,2,3”的全排列,依次是:

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

所以题目的意思是,从上面的某一行重排到期下一行,如果已经是最后一行了,则重排成第一行。

但是也不能根据给出的数组中的数字列出所有排列,因为要求不能占用额外的空间。

分析

网上看来一个示例,觉得挺好的,也没必要另外找一个了。

6 5 4 8 7 5 1

一开始没看对方的后面介绍,就自己在想这个排列的下一个排列是怎样的。

首先肯定从后面开始看,1和5调换了没有用。

7、5和1调换了也没有效果,因此而发现了8、7、5、1是递减的。

如果想要找到下一个排列,找到递增的位置是关键。

因为在这里才可以使其增长得更大。

于是找到了4,显而易见4过了是5而不是8或者7更不是1。

因此就需要找出比4大但在这些大数里面最小的值,并将其两者调换。

那么整个排列就成了:6 5 5 8 7 4 1

然而最后一步将后面的8 7 4 1做一个递增。
class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        //例子6 5 4 8 7 5 1 
        //首先找到递增的下标值
        int index = nums.size() -1;
        while(index > 0){
             if(nums[index] > nums[index - 1]){
                break;
             }
            index--;
        }//此时的index指向要交换节点的下一个节点8
        if(index == 0){
            //已经是排列的最后一项,返回排列组合第一个
            sort(nums.begin(),nums.end());
            return ;
        }
 
        
        int exchangeIndex;
        for(int i = nums.size()-1; i >= index; --i){
            if(nums[i] > nums[index-1]){
                //因为8751都是递减,所以第一个大于4且最小的值是5;
                exchangeIndex = i;
                break;
            }
        }
        swap(nums[index-1],nums[exchangeIndex]);
        //最后将8741做一个递增
        sort(nums.begin()+index, nums.end());
    }
};
leetcode编译通过.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值