题目地址
解题方法
这道题是一个既有的算法,维基百科地址:Permutation - Wikipedia,原文如下:
The following algorithm generates the next permutation lexicographically after a given permutation. It changes the given permutation in-place.
- Find the largest index k such that
a[k] < a[k + 1]
. If no such index exists, the permutation is the last permutation.- Find the largest index l greater than k such that
a[k]
<a[l]
.- Swap the value of
a[k]
with that ofa[l]
.- Reverse the sequence from
a[k + 1]
up to and including the final elementa[n]
.
翻译过来就是:
以下算法给出了生成某个全排列的字典序中的下一个全排列的方法,该算法是原地工作的。
- 找到最大的满足
a[k] < a[k + 1]
的下标k
(也就是最后一个升序序列的起点),如果找不到,则该全排列就是最后一个全排列(即整个数组为一个降序序列。按题目要求,我们要翻转整个数组)。- 找到最大的满足
a[k] < a[l]
的下标l
(也就是从下标k
开始比a[k]
大的第一个数)。- 交换
a[k]
和a[l]
的值。- 将数组从
a[k + 1]
开始到数组末尾的部分翻转(此时这部分是一个升序序列)。
按照这个算法实现即可。这里我用 i
和 j
代表算法描述中的 k
和 k + 1
,用 k
代表 l
,并且从后往前遍历数组。
复杂度分析
时间复杂度:O(n),需要遍历数组三次,前两次找到 i
和 j
,第三次翻转 nums[j:]
。
空间复杂度:O(1),只使用了常数个数的存储空间。
AC 代码
1 | func nextPermutation(nums []int) { |
About this Post
This post is written by Noelle Mu, licensed under CC BY-NC 4.0.