282.expression-add-operators.go 974 B

123456789101112131415161718192021222324252627282930313233343536
  1. func addOperators(num string, target int) (res []string) {
  2. strlen := len(num)
  3. exp := make([]byte, 2*strlen)
  4. DFS(num, strlen, target, 0, &exp, 0, 0, 0, &res) // O(n^4) time, O(n) space
  5. return
  6. }
  7. func DFS(num string, strlen, target, pos int, exp *[]byte, length, prev, curr int, res *[]string) {
  8. if pos == strlen && curr == target {
  9. *res = append(*res, string((*exp)[0:length]))
  10. return
  11. }
  12. n, i, l := 0, pos, length
  13. if pos != 0 {
  14. length++
  15. }
  16. for i < strlen {
  17. if num[pos] == '0' && pos < i { // Avoid leading zero
  18. break
  19. }
  20. n = n*10 + int(num[i]-'0')
  21. (*exp)[length] = num[i]
  22. length, i = length+1, i+1
  23. if pos == 0 { // Init DFS
  24. DFS(num, strlen, target, i, exp, length, n, n, res)
  25. continue
  26. }
  27. (*exp)[l] = '+'
  28. DFS(num, strlen, target, i, exp, length, n, curr+n, res)
  29. (*exp)[l] = '-'
  30. DFS(num, strlen, target, i, exp, length, -n, curr-n, res)
  31. (*exp)[l] = '*'
  32. DFS(num, strlen, target, i, exp, length, prev*n, curr-prev+prev*n, res)
  33. }
  34. }