Skip to content

Instantly share code, notes, and snippets.

@whiledoing
Created June 9, 2018 09:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whiledoing/d4386bfc214a3ba6c6fce9de76800b59 to your computer and use it in GitHub Desktop.
Save whiledoing/d4386bfc214a3ba6c6fce9de76800b59 to your computer and use it in GitHub Desktop.
[python-next-permutation] next permuation of list of elements #python #algorithm
def next_permutation(nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if not nums: return nums
l = len(nums)
i, j = l - 2, l - 1
while i >= 0 and nums[i] >= nums[i + 1]:
i -= 1
if i == -1:
nums = nums[::-1]
return
while j > i and nums[j] <= nums[i]:
j -= 1
nums[i], nums[j] = nums[j], nums[i]
nums[i + 1:] = nums[i + 1:][::-1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment