14
14
class ExpressionAddOperators {
15
15
func addOperators( _ num: String , _ target: Int ) -> [ String ] {
16
16
var res = [ String] ( )
17
- let numChars = Array ( num. characters)
18
-
19
- guard numChars. count > 0 else {
17
+
18
+ guard num. count > 0 else {
20
19
return res
21
20
}
22
-
23
- dfs ( & res, " " , numChars , target, 0 , 0 , 0 )
24
-
21
+
22
+ dfs ( & res, " " , num , target, 0 , 0 , 0 )
23
+
25
24
return res
26
25
}
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 {
26
+
27
+ private func dfs( _ res: inout [ String ] , _ temp: String , _ num : String , _ target: Int , _ pos: Int , _ eval: Int , _ mul: Int ) {
28
+ if pos == num . count {
30
29
if eval == target {
31
30
res. append ( temp)
32
31
}
33
32
return
34
33
}
35
-
36
- for i in pos..< numChars . count {
37
- if i != pos && numChars [ pos ] == " 0 " {
34
+
35
+ for i in pos..< num . count {
36
+ if i != pos && num [ i ] == " 0 " {
38
37
break
39
38
}
40
- let curt = Int ( String ( numChars [ pos..< i + 1 ] ) ) !
39
+ let curt = Int ( num [ pos..< i + 1 ] ) !
41
40
if pos == 0 {
42
- dfs ( & res, temp + String( curt) , numChars , target, i + 1 , curt, curt)
41
+ dfs ( & res, temp + String( curt) , num , target, i + 1 , curt, curt)
43
42
} 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)
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
46
}
48
47
}
49
48
}
49
+ }
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
+ }
50
69
}
0 commit comments