|
@@ -1,30 +1,36 @@
|
|
-import (
|
|
|
|
- "strconv"
|
|
|
|
-)
|
|
|
|
-
|
|
|
|
func addOperators(num string, target int) (res []string) {
|
|
func addOperators(num string, target int) (res []string) {
|
|
- DFS(num, target, 0, "", 0, 0, &res)
|
|
|
|
|
|
+ strlen := len(num)
|
|
|
|
+ exp := make([]byte, 2*strlen)
|
|
|
|
+ DFS(num, strlen, target, 0, &exp, 0, 0, 0, &res) // O(n^4) time, O(n) space
|
|
return
|
|
return
|
|
}
|
|
}
|
|
|
|
|
|
-func DFS(num string, target int, pos int, exp string, prev int, curr int, res *[]string) {
|
|
|
|
- if pos == len(num) && curr == target {
|
|
|
|
- *res = append(*res, exp)
|
|
|
|
|
|
+func DFS(num string, strlen, target, pos int, exp *[]byte, length, prev, curr int, res *[]string) {
|
|
|
|
+ if pos == strlen && curr == target {
|
|
|
|
+ *res = append(*res, string((*exp)[0:length]))
|
|
return
|
|
return
|
|
}
|
|
}
|
|
- for i := pos; i < len(num); i++ {
|
|
|
|
|
|
+ n, i, l := 0, pos, length
|
|
|
|
+ if pos != 0 {
|
|
|
|
+ length++
|
|
|
|
+ }
|
|
|
|
+ for i < strlen {
|
|
if num[pos] == '0' && pos < i { // Avoid leading zero
|
|
if num[pos] == '0' && pos < i { // Avoid leading zero
|
|
break
|
|
break
|
|
}
|
|
}
|
|
- str := num[pos:i+1]
|
|
|
|
- n, _ := strconv.Atoi(str)
|
|
|
|
|
|
+ n = n*10 + int(num[i]-'0')
|
|
|
|
+ (*exp)[length] = num[i]
|
|
|
|
+ length, i = length+1, i+1
|
|
if pos == 0 { // Init DFS
|
|
if pos == 0 { // Init DFS
|
|
- DFS(num, target, i+1, str, n, n, res)
|
|
|
|
|
|
+ DFS(num, strlen, target, i, exp, length, n, n, res)
|
|
continue
|
|
continue
|
|
}
|
|
}
|
|
- DFS(num, target, i+1, exp+"+"+str, n, curr+n, res)
|
|
|
|
- DFS(num, target, i+1, exp+"-"+str, -n, curr-n, res)
|
|
|
|
- DFS(num, target, i+1, exp+"*"+str, prev*n, curr-prev+prev*n, res)
|
|
|
|
|
|
+ (*exp)[l] = '+'
|
|
|
|
+ DFS(num, strlen, target, i, exp, length, n, curr+n, res)
|
|
|
|
+ (*exp)[l] = '-'
|
|
|
|
+ DFS(num, strlen, target, i, exp, length, -n, curr-n, res)
|
|
|
|
+ (*exp)[l] = '*'
|
|
|
|
+ DFS(num, strlen, target, i, exp, length, prev*n, curr-prev+prev*n, res)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
|