-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathPermutations.py
More file actions
40 lines (29 loc) · 818 Bytes
/
Permutations.py
File metadata and controls
40 lines (29 loc) · 818 Bytes
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
import copy
# Given a collection of distinct integers, return all possible permutations.
# Example:
# Input: [1,2,3]
# Output:
# [
# [1,2,3],
# [1,3,2],
# [2,1,3],
# [2,3,1],
# [3,1,2],
# [3,2,1]
# ]
def permutation_recursive(nums, path):
#### Base case return [combination] list of list
# for example [[1,2,3]]+[[2,3,4]] =>> [[1,2,3],[2,3,4]]
if len(nums) == 0:
return [path]
output = []
for i in range(len(nums)):
copy_path = copy.deepcopy(path)
copy_path.append(nums[i])
permutations = permutation_recursive(nums[:i] + nums[i + 1:], copy_path)
output += permutations
return output
def permute(nums):
return permutation_recursive(nums, [])
print(permute([1, 2, 3]))
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]