File tree Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments