|
14 | 14 | class ExpressionAddOperators { |
15 | 15 | func addOperators(_ num: String, _ target: Int) -> [String] { |
16 | 16 | 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 | + |
24 | 20 | return res |
25 | 21 | } |
26 | 22 |
|
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 { |
29 | 25 | if eval == target { |
30 | | - res.append(temp) |
| 26 | + res.append(candidate) |
31 | 27 | } |
| 28 | + |
32 | 29 | return |
33 | 30 | } |
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" { |
37 | 35 | break |
38 | 36 | } |
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) |
42 | 46 | } 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) |
46 | 50 | } |
47 | 51 | } |
48 | 52 | } |
49 | 53 | } |
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