题意:就是生成比这个排列大的下一个排列,如果排列已经最大了,就直接生成最小的下一个排列。
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
思路:对于这一类排列的问题,都是有一个大概的思路的,都有一点像递归或者动态规划的感觉,首先,找到最长的非增后缀,然后将后缀的前一位设为标志位,再从后缀中从后往前地找出第一个大于标志位的数,把它和标志位调换顺序,最后把后缀反转一下就ok了。其实就是相当于找出临界的后缀,再对应改变前一位,之后将后缀化为最小的结果。这题具体思路可以看这个思路。
class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
i, j = len(nums)-2, len(nums)-1
while nums[i+1] <= nums[i] and i >= 0:
i -= 1
if i < 0:
nums = nums[::-1]
else:
while nums[i] >= nums[j] and j > 0:
j -= 1
nums[i], nums[j] = nums[j], nums[i]
nums[i+1:] = nums[len(nums)-1:i:-1]