forked from MTrajK/coding-problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpermutations.py
More file actions
58 lines (44 loc) · 1.18 KB
/
permutations.py
File metadata and controls
58 lines (44 loc) · 1.18 KB
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
51
52
53
54
55
56
57
58
'''
Permutations
Given a collection of distinct integers, return all possible permutations.
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
=========================================
A classical recursive algorithm for permutations.
Time Complexity: O(N!)
Space Complexity: O(N!)
'''
############
# Solution #
############
def permutations(nums):
result = []
if len(nums) == 0:
return result
permute(result, set(nums), [])
return result
def permute(result, nums, permutation):
if len(nums) == 0:
result.append([num for num in permutation])
else:
for num in list(nums): # create a new object with the same values because nums will be changed later
nums.remove(num)
permutation.append(num)
permute(result, nums, permutation)
# reset the structures
del permutation[-1]
nums.add(num)
###########
# Testing #
###########
# Test 1
# Correct result => [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
print(permutations([1, 2, 3]))