31. Next Permutation
Medium
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 and use only constant 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
😇 Solution
class Solution:
def permutation(lst,x):
res = []
if len(lst) < 1:
res.append(x)
return res
for l in lst:
for i in range(len(l)+1):
temp = l[:i] + x + l[i:]
if temp not in res:
res.append(temp)
return res
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
st = ''
for n in nums:
st += str(n)
lst = []
for s in st:
lst = Solution.permutation(lst,s)
lst.sort()
i = 0
while(i <= len(lst)-2):
if lst[i] == st:
nums[:] = list(lst[i+1])
break
i += 1
if i == len(lst)-1:
nums[:] = list(lst[0])
Last updated
Was this helpful?