1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
def next_permutation(nums):
N = len(nums)
i = N - 2
# find reversed-order from right to left
while i >= 0 and nums[i] >= nums[i+1]:
i -= 1
# the nums is fully reversed-order
if i == -1:
return nums[::-1]
else:
# find the first j is greater than i
j = N - 1
while j >= 0 and nums[j] <= nums[i]:
j -= 1
nums[i], nums[j] = nums[j], nums[i]
# reverse i-right, make it the smallest permutation (compare to current)
l, r = i+1, N-1
while l < r:
nums[l], nums[r] = nums[r], nums[l]
l += 1
r -= 1
return nums
|