Skip to content

Commit 074dc16

Browse files
author
Yi Gu
committed
[DFS] add Solutions to Combination Sum and Letter Combinations of a Phone Number
1 parent 2460f12 commit 074dc16

File tree

2 files changed

+100
-0
lines changed

2 files changed

+100
-0
lines changed

DFS/CombinationSum.swift

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/combination-sum/
3+
* Primary idea: Classic Depth-first Search
4+
*
5+
* Time Complexity: O(n^n), Space Complexity: O(n)
6+
*
7+
*/
8+
9+
class CombinationSum {
10+
func combinationSum(candidates: [Int], _ target: Int) -> [[Int]] {
11+
var res = [[Int]]()
12+
13+
guard candidates.count > 0 else {
14+
return res
15+
}
16+
17+
var path = [Int]()
18+
let candidates = candidates.sort({$0 < $1})
19+
20+
_dfs(candidates, target, &res, &path, 0)
21+
22+
return res
23+
}
24+
25+
private func _dfs(candidates: [Int], _ target: Int, inout _ res: [[Int]], inout _ path: [Int], _ index: Int) {
26+
if target == 0 {
27+
res.append([Int](path))
28+
return
29+
}
30+
31+
for i in index ..< candidates.count {
32+
guard candidates[i] <= target else {
33+
break
34+
}
35+
36+
path.append(candidates[i])
37+
_dfs(candidates, target - candidates[i], &res, &path, i)
38+
path.removeLast()
39+
}
40+
}
41+
}
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/letter-combinations-of-a-phone-number/
3+
* Primary idea: Classic Depth-first Search, create phone board at first
4+
*
5+
* Time Complexity: O(nm), m stands for the average size of a string represented by a number
6+
* Space Complexity: O(n)
7+
*
8+
*/
9+
10+
class LetterCombinationsPhoneNumber {
11+
func letterCombinations(digits: String) -> [String] {
12+
var res = [String]()
13+
let chars = [Character](digits.characters)
14+
15+
guard chars.count > 0 else {
16+
return res
17+
}
18+
19+
let board = _init()
20+
21+
_dfs(&res, board, chars, "", 0)
22+
23+
return res
24+
}
25+
26+
private func _init() -> [String] {
27+
var res = [String]()
28+
29+
res.append("")
30+
res.append("")
31+
res.append("abc")
32+
res.append("def")
33+
res.append("ghi")
34+
res.append("jkl")
35+
res.append("mno")
36+
res.append("pqrs")
37+
res.append("tuv")
38+
res.append("wxyz")
39+
40+
return res
41+
}
42+
43+
private func _dfs(inout res: [String], _ board: [String], _ chars: [Character], _ temp: String, _ index: Int) {
44+
// termination case
45+
if index == chars.count {
46+
res.append(temp)
47+
return
48+
}
49+
50+
var temp = temp
51+
let current = [Character](board[Int(String(chars[index]))!].characters)
52+
53+
for i in 0 ..< current.count {
54+
temp += String(current[i])
55+
_dfs(&res, board, chars, temp, index + 1)
56+
temp = String(temp.characters.dropLast())
57+
}
58+
}
59+
}

0 commit comments

Comments
 (0)