mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
Update permutations.py (#8102)
This commit is contained in:
parent
c93659d7ce
commit
4a27b54430
|
@ -1,7 +1,6 @@
|
|||
def permute(nums: list[int]) -> list[list[int]]:
|
||||
"""
|
||||
Return all permutations.
|
||||
|
||||
>>> from itertools import permutations
|
||||
>>> numbers= [1,2,3]
|
||||
>>> all(list(nums) in permute(numbers) for nums in permutations(numbers))
|
||||
|
@ -20,7 +19,32 @@ def permute(nums: list[int]) -> list[list[int]]:
|
|||
return result
|
||||
|
||||
|
||||
def permute2(nums):
|
||||
"""
|
||||
Return all permutations of the given list.
|
||||
|
||||
>>> permute2([1, 2, 3])
|
||||
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2]]
|
||||
"""
|
||||
|
||||
def backtrack(start):
|
||||
if start == len(nums) - 1:
|
||||
output.append(nums[:])
|
||||
else:
|
||||
for i in range(start, len(nums)):
|
||||
nums[start], nums[i] = nums[i], nums[start]
|
||||
backtrack(start + 1)
|
||||
nums[start], nums[i] = nums[i], nums[start] # backtrack
|
||||
|
||||
output = []
|
||||
backtrack(0)
|
||||
return output
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import doctest
|
||||
|
||||
# use res to print the data in permute2 function
|
||||
res = permute2([1, 2, 3])
|
||||
print(res)
|
||||
doctest.testmod()
|
||||
|
|
Loading…
Reference in New Issue
Block a user