Skip to content

Commit ec49d72

Browse files
sangheestylekamyu104
authored andcommitted
add DFS solution (#51)
* add DFS solution * Update permutations.py
1 parent 3566782 commit ec49d72

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Python/permutations.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,32 @@ def permuteRecu(self, result, used, cur, num):
2222
cur.pop()
2323
used[i] = False
2424

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

Comments
 (0)