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