Skip to content

Commit 4032088

Browse files
committed
Refactor solution to Expression Add Operators
1 parent 0550b87 commit 4032088

File tree

1 file changed

+23
-39
lines changed

1 file changed

+23
-39
lines changed

DFS/ExpressionAddOperators.swift

Lines changed: 23 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -14,56 +14,40 @@
1414
class ExpressionAddOperators {
1515
func addOperators(_ num: String, _ target: Int) -> [String] {
1616
var res = [String]()
17-
18-
guard num.count > 0 else {
19-
return res
20-
}
21-
22-
dfs(&res, "", num, target, 0, 0, 0)
23-
17+
18+
dfs(Array(num), 0, target, 0, 0, &res, "")
19+
2420
return res
2521
}
2622

27-
private func dfs(_ res: inout [String], _ temp: String, _ num: String, _ target: Int, _ pos: Int, _ eval: Int, _ mul: Int) {
28-
if pos == num.count {
23+
private func dfs(_ nums: [Character], _ index: Int, _ target: Int, _ eval: Int, _ mul: Int, _ res: inout [String], _ candidate: String) {
24+
if index == nums.count {
2925
if eval == target {
30-
res.append(temp)
26+
res.append(candidate)
3127
}
28+
3229
return
3330
}
34-
35-
for i in pos..<num.count {
36-
if i != pos && num[pos] == "0" {
31+
32+
for i in index..<nums.count {
33+
// edge case: "305", 15 -> []
34+
if i != index && nums[index] == "0" {
3735
break
3836
}
39-
let curt = Int(num[pos..<i + 1])!
40-
if pos == 0 {
41-
dfs(&res, temp + String(curt), num, target, i + 1, curt, curt)
37+
38+
let curStr = String(nums[index...i])
39+
40+
guard let cur = Int(curStr) else {
41+
fatalError("Invalid input: num")
42+
}
43+
44+
if index == 0 {
45+
dfs(nums, i + 1, target, cur, cur, &res, curStr)
4246
} else {
43-
dfs(&res, temp + "+" + String(curt), num, target, i + 1, eval + curt, curt)
44-
dfs(&res, temp + "-" + String(curt), num, target, i + 1, eval - curt, -curt)
45-
dfs(&res, temp + "*" + String(curt), num, target, i + 1, eval - mul + mul * curt, mul * curt)
47+
dfs(nums, i + 1, target, eval + cur, cur, &res, candidate + "+" + curStr)
48+
dfs(nums, i + 1, target, eval - cur, -cur, &res, candidate + "-" + curStr)
49+
dfs(nums, i + 1, target, eval - mul + mul * cur, mul * cur, &res, candidate + "*" + curStr)
4650
}
4751
}
4852
}
4953
}
50-
51-
extension String {
52-
subscript(index: Int) -> String {
53-
get {
54-
assert(index < self.count)
55-
return String(Array(self.characters)[index])
56-
}
57-
}
58-
59-
subscript(range: CountableRange<Int>) -> String {
60-
get {
61-
var result = ""
62-
for i in range {
63-
assert(i < self.count)
64-
result.append(self[i])
65-
}
66-
return result
67-
}
68-
}
69-
}

0 commit comments

Comments
 (0)