【leetcode刷题笔记】Next Permutation

本文介绍了一种寻找给定数字序列的下一个字典序排列的方法。通过四个步骤:找到第一个下降元素、找到该元素右侧的最小较大值、交换这两个元素并反转后续序列来实现。特别讨论了特定情况下的处理。

摘要生成于 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 1,2,31,3,2
2 3,2,11,2,3
3 1,1,51,5,1

题解:字典序法

步骤:

1.从右向左找出第一个比它右边数字小的数,记为a;

2.找出a右边比它大的最小的数,记为b;

3.交换a和b;

4.reverse原来a所在位置后面所有的元素。

代码:

 1 class Solution {
 2 public:
 3     void nextPermutation(vector<int> &num) {
 4         int n = num.size();
 5         int j;
 6         for(j = n-2;j >= 0;j --){
 7             if(num[j] < num[j+1])
 8             {
 9                 //与右边比它大的最小的数互相换位
10                 int min_index = n-1;
11                 int minmum = 32767;
12                 for(int u = n-1;u > j;u --)
13                     if(num[u] > num[j]){
14                         if(num[u] < minmum){
15                             min_index = u;
16                             minmum = num[u];
17                         }
18                         break;
19                     }
20 
21                 char temp = num[min_index];
22                 num[min_index] = num[j];
23                 num[j] = temp;
24                 reverse(num.begin()+j+1,num.end());
25                 break;
26 
27             }
28         }
29         if(j < 0)
30             reverse(num.begin(),num.end());
31     }
32 };

有一种类似321这种序列的情况,它的下一个排列是123,字典序法是找不出来的,所以在代码29行单独加了一个判断,如果遇到这样的序列,直接倒置返回就可以了。

转载于:https://www.cnblogs.com/sunshineatnoon/p/3696611.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值