-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path46_Permutations.py
More file actions
40 lines (34 loc) · 1.22 KB
/
46_Permutations.py
File metadata and controls
40 lines (34 loc) · 1.22 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
# 1 Possible Solution
# 1. Backtracking
class Solution:
# Time: O(N*2^N), Space: O(N*N!)
def permutations(nums):
if not nums:
return []
def backtrack(Idx = 0):
if Idx == lengthOfNums:
result.append(nums[:])
for j in range(Idx, lengthOfNums):
swap(nums, Idx, j)
backtrack(Idx + 1)
# backtrack
swap(nums, Idx, j)
def swap(array, x, y):
array[x], array[y] = array[y], array[x]
result = []
lengthOfNums = len(nums)
backtrack()
return result
# Python Slicing
def getPermutations(array):
permutations = []
permutationsHelper(array, [], permutations)
return permutations
def permutationsHelper(array, currentPermutation, permutations):
if not len(array) and len(currentPermutation):
permutations.append(currentPermutation)
else:
for i in range(len(array)):
newArray = array[:i] + array[i + 1 :]
newPermutation = currentPermutation + [array[i]]
permutationsHelper(newArray, newPermutation, permutations)