Created
June 9, 2018 09:55
-
-
Save whiledoing/d4386bfc214a3ba6c6fce9de76800b59 to your computer and use it in GitHub Desktop.
[python-next-permutation] next permuation of list of elements #python #algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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