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 3566782 commit ec49d72Copy full SHA for ec49d72
Python/permutations.py
@@ -22,3 +22,32 @@ def permuteRecu(self, result, used, cur, num):
22
cur.pop()
23
used[i] = False
24
25
+
26
+# Time: O(n^2 * n!)
27
+# Space: O(n^2)
28
+class Solution2(object):
29
+ def permute(self, nums):
30
+ """
31
+ :type nums: List[int]
32
+ :rtype: List[List[int]]
33
34
+ res = []
35
+ self.dfs(nums, [], res)
36
+ return res
37
38
+ def dfs(self, nums, path, res):
39
+ if not nums:
40
+ res.append(path)
41
42
+ for i in xrange(len(nums)):
43
+ # e.g., [1, 2, 3]: 3! = 6 cases
44
+ # idx -> nums, path
45
+ # 0 -> [2, 3], [1] -> 0: [3], [1, 2] -> [], [1, 2, 3]
46
+ # -> 1: [2], [1, 3] -> [], [1, 3, 2]
47
+ #
48
+ # 1 -> [1, 3], [2] -> 0: [3], [2, 1] -> [], [2, 1, 3]
49
+ # -> 1: [1], [2, 3] -> [], [2, 3, 1]
50
51
+ # 2 -> [1, 2], [3] -> 0: [2], [3, 1] -> [], [3, 1, 2]
52
+ # -> 1: [1], [3, 2] -> [], [3, 2, 1]
53
+ self.dfs(nums[:i] + nums[i+1:], path + [nums[i]], res)
0 commit comments