Skip to content

Commit ec99f02

Browse files
author
wuduhren
committed
permutation
1 parent aa833bb commit ec99f02

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

problems/python3/permutations.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""
2+
Time: O(N!), since we call helper() N! times.
3+
Space: O(N) for recursion stacks.
4+
5+
Whenever we call `helper()`, we pick a num that is not "used" and add it to the `permutation`.
6+
Recursively call the `helper()` until we filled the `permutation`.
7+
Resotre `permutation` and `used` and try another `num`.
8+
"""
9+
class Solution:
10+
def permute(self, nums: List[int]) -> List[List[int]]:
11+
def helper():
12+
if len(permutation)==len(nums):
13+
ans.append(permutation.copy())
14+
return
15+
16+
for num in nums:
17+
if num in used: continue
18+
used.add(num)
19+
permutation.append(num)
20+
helper()
21+
used.remove(num)
22+
permutation.pop()
23+
24+
ans = []
25+
permutation = []
26+
used = set()
27+
helper()
28+
return ans

0 commit comments

Comments
 (0)