forked from wuduhren/leetcode-python
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpermutations.py
More file actions
28 lines (25 loc) · 870 Bytes
/
permutations.py
File metadata and controls
28 lines (25 loc) · 870 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
"""
Time: O(N!), since we call helper() N! times.
Space: O(N) for recursion stacks.
Whenever we call `helper()`, we pick a num that is not "used" and add it to the `permutation`.
Recursively call the `helper()` until we filled the `permutation`.
Resotre `permutation` and `used` and try another `num`.
"""
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
def helper():
if len(permutation)==len(nums):
ans.append(permutation.copy())
return
for num in nums:
if num in used: continue
used.add(num)
permutation.append(num)
helper()
used.remove(num)
permutation.pop()
ans = []
permutation = []
used = set()
helper()
return ans