[LeetCode] 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

» Solve this problem

[解题思路]
这题更像一道数学题,画了个图表示算法,如下:

[Code]

1:      void nextPermutation(vector<int> &num) {   
2: // Start typing your C/C++ solution below
3: // DO NOT write int main() function
4: assert(num.size() >0);
5: int vioIndex = num.size() -1;
6: while(vioIndex >0)
7: {
8: if(num[vioIndex-1] < num[vioIndex])
9: break;
10: vioIndex --;
11: }
12: if(vioIndex >0)
13: {
14: vioIndex--;
15: int rightIndex = num.size()-1;
16: while(rightIndex >=0 && num[rightIndex] <= num[vioIndex])
17: {
18: rightIndex --;
19: }
20: int swap = num[vioIndex];
21: num[vioIndex] = num[rightIndex];
22: num[rightIndex] = swap;
23: vioIndex++;
24: }
25: int end= num.size()-1;
26: while(end > vioIndex)
27: {
28: int swap = num[vioIndex];
29: num[vioIndex] = num[end];
30: num[end] = swap;
31: end--;
32: vioIndex++;
33: }
34: }

[已犯错误]
1. Line 16
要找的是右边第一个大于violate number的值,而不是等于。如果代码写成
while(rightIndex >=0 && num[rightIndex] < num[vioIndex]) 
那么在处理[1,5,1]时,会返回[1,1,5],而不是[5,1,1]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值