Skip to content

Commit a6af4cd

Browse files
authored
Merge pull request soapyigu#196 from soapyigu/DFS
[DFS] Add a solution to Expression Add Operators
2 parents e13b84c + b8a2e77 commit a6af4cd

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

DFS/ExpressionAddOperators.swift

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/expression-add-operators/
3+
* Primary idea: Classic Depth-first Search, terminates at when position encounters the
4+
* length of the string num, add to result when eval is equal to target
5+
*
6+
* Note:
7+
* 1. String cast to Integer will make character loss, e.g. "05" -> 5
8+
* 2. Multiplication's priority is higher than addiction
9+
*
10+
* Time Complexity: O(n!), Space Complexity: O(n)
11+
*
12+
*/
13+
14+
class ExpressionAddOperators {
15+
func addOperators(_ num: String, _ target: Int) -> [String] {
16+
var res = [String]()
17+
let numChars = Array(num.characters)
18+
19+
guard numChars.count > 0 else {
20+
return res
21+
}
22+
23+
dfs(&res, "", numChars, target, 0, 0, 0)
24+
25+
return res
26+
}
27+
28+
private func dfs(_ res: inout [String], _ temp: String, _ numChars: [Character], _ target: Int, _ pos: Int, _ eval: Int, _ mul: Int) {
29+
if pos == numChars.count {
30+
if eval == target {
31+
res.append(temp)
32+
}
33+
return
34+
}
35+
36+
for i in pos ..< numChars.count {
37+
if i != pos && numChars[pos] == "0" {
38+
break
39+
}
40+
let curt = Int(String(numChars[pos ..< i + 1]))!
41+
if pos == 0 {
42+
dfs(&res, temp + String(curt), numChars, target, i + 1, curt, curt)
43+
} else {
44+
dfs(&res, temp + "+" + String(curt), numChars, target, i + 1, eval + curt, curt)
45+
dfs(&res, temp + "-" + String(curt), numChars, target, i + 1, eval - curt, -curt)
46+
dfs(&res, temp + "*" + String(curt), numChars, target, i + 1, eval - mul + mul * curt, mul * curt)
47+
}
48+
}
49+
}
50+
}

0 commit comments

Comments
 (0)