-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPermutations.py
52 lines (33 loc) · 1.3 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
51
52
# Time Complexity - O(N*N!)
# Space complexity - O(N*N!)
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
return self.checkPermutation(nums,[],[])
def checkPermutation(self,nums,result,path):
if len(path) == len(nums):
result.append(path[:])
return result
for i in range(len(nums)):
# to remove repetition
if nums[i] in path:
continue
path.append(nums[i])
result = self.checkPermutation(nums,result,path)
path.pop()
return result
# Time Complexity - O(N!)
# Space complexity - O(N!)
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
return self.checkPermutation(nums,0,[])
def checkPermutation(self,nums,start,result):
if start == len(nums):
result.append(nums[:])
return result
for i in range(start,len(nums)):
# Swap the current element with the start element
nums[i] , nums[start] = nums[start],nums[i]
result = self.checkPermutation(nums,start+1,result)
# Swap back to backtrack
nums[i] , nums[start] = nums[start],nums[i]
return result