We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent aa833bb commit ec99f02Copy full SHA for ec99f02
problems/python3/permutations.py
@@ -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
28
+ return ans
0 commit comments