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
间隔了一个月没有刷题了~这是到美国后写的第一道题,写的时候一直在走神,好在看了解题思路后还是能自己写出代码~
思路参考自http://blog.youkuaiyun.com/linhuanmars/article/details/20434115 大概如下
比如排列是(2,3,6,5,4,1),求下一个排列的基本步骤是这样:
1) 先从后往前找到第一个不是依次增长的数,记录下位置p。比如例子中的3,对应的位置是1;
2) 接下来分两种情况:
(1) 如果上面的数字都是依次增长的,那么说明这是最后一个排列,下一个就是第一个,其实把所有数字反转过来即可(比如(6,5,4,3,2,1)下一个是(1,2,3,4,5,6));
(2) 否则,如果p存在,从p开始往后找,找到下一个数就比p对应的数小的数字,然后两个调换位置,比如例子中的4。调换位置后得到(2,4,6,5,3,1)。最后把p之后的所有数字倒序,比如例子中得到(2,4,1,3,5,6), 这个即是要求的下一个排列。
class Solution:
# @param num, a list of integer
# @return nothing (void), do not return anything, modify num in-place instead.
def nextPermutation(self, num):
if num is None or len(num) == 0: return
p = -1
for i in xrange(len(num) - 2, -1, -1):
if num[i] < num[i + 1]:
p = i
break
if p == -1:
num.reverse()
return
for i in xrange(len(num) - 1, p, -1):
if num[i] > num[p]:
num[i], num[p] = num[p], num[i]
break
i, j = p + 1, len(num) - 1
while i < j:
num[i], num[j] = num[j], num[i]
i += 1; j -= 1

本文介绍如何实现将一组数字重新排列为字典序中下一个更大的排列。若无法形成更大的排列,则将其排列为最小的顺序。文章详细解释了算法思路,并提供了一个Python实现示例。
423

被折叠的 条评论
为什么被折叠?



