241.different-ways-to-add-parentheses.go 754 B

123456789101112131415161718192021222324252627282930313233
  1. import (
  2. "strconv"
  3. )
  4. var m map[string][]int = make(map[string][]int)
  5. func diffWaysToCompute(input string) (ans []int) {
  6. if _, ok := m[input]; ok {
  7. return m[input]
  8. }
  9. for i := range input { // Divide and conquer, use every operator to split input into 2 smaller sub-problems.
  10. if ch := input[i]; ch == '+' || ch == '-' || ch == '*' {
  11. for _, l := range diffWaysToCompute(input[:i]) {
  12. for _, r := range diffWaysToCompute(input[i+1:]) {
  13. if ch == '+' {
  14. ans = append(ans, l+r)
  15. } else if ch == '-' {
  16. ans = append(ans, l-r)
  17. } else {
  18. ans = append(ans, l*r)
  19. }
  20. }
  21. }
  22. }
  23. }
  24. if len(ans) == 0 { // No operator, just a number
  25. n, _ := strconv.Atoi(input)
  26. ans = append(ans, n)
  27. }
  28. m[input] = ans
  29. return
  30. }