forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
permutations.py
50 lines (42 loc) · 1.25 KB
/
permutations.py
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
38
39
40
41
42
43
44
45
46
47
48
49
50
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))
True
"""
result = []
if len(nums) == 1:
return [nums.copy()]
for _ in range(len(nums)):
n = nums.pop(0)
permutations = permute(nums)
for perm in permutations:
perm.append(n)
result.extend(permutations)
nums.append(n)
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()