-
Notifications
You must be signed in to change notification settings - Fork 1
/
Q31 Next Permutation
37 lines (31 loc) · 1017 Bytes
/
Q31 Next Permutation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution:
def swap(self, nums, ind1, ind2):
temp = nums[ind1]
nums[ind1] = nums[ind2]
nums[ind2] = temp
def reverse(self, nums, start, end):
while start < end:
self.swap(nums, start, end)
start += 1
end -= 1
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
#base case
if not nums:
return
if len(nums) == 1:
return nums
if len(nums) == 2:
return self.swap(nums, 0, 1)
dec = len(nums) - 2
while dec >= 0 and nums[dec] >= nums[dec + 1]:
dec -= 1
self.reverse(nums, dec + 1, len(nums) - 1)
if dec == -1:
return
next_num = dec + 1
while next_num < len(nums) and nums[next_num] <= nums[dec]:
next_num += 1
self.swap(nums, next_num, dec)