|
@@ -1,15 +1,30 @@
|
|
|
-package main
|
|
|
-
|
|
|
import (
|
|
|
- "fmt"
|
|
|
+ "strconv"
|
|
|
)
|
|
|
|
|
|
-func addOperators(num string, target int) []string {
|
|
|
-
|
|
|
+func addOperators(num string, target int) (res []string) {
|
|
|
+ DFS(num, target, 0, "", 0, 0, &res)
|
|
|
+ return
|
|
|
}
|
|
|
|
|
|
-func dfs(res *[]string, num string, target)
|
|
|
-
|
|
|
-func main() {
|
|
|
- fmt.Println(addOperators("105", 5))
|
|
|
+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)
|
|
|
+ return
|
|
|
+ }
|
|
|
+ for i := pos; i < len(num); i++ {
|
|
|
+ if num[pos] == '0' && pos < i { // Avoid leading zero
|
|
|
+ break
|
|
|
+ }
|
|
|
+ str := num[pos:i+1]
|
|
|
+ n, _ := strconv.Atoi(str)
|
|
|
+ if pos == 0 { // Init DFS
|
|
|
+ DFS(num, target, i+1, str, n, n, res)
|
|
|
+ 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)
|
|
|
+ }
|
|
|
}
|
|
|
+
|