1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// @Title: 为运算表达式设计优先级 (Different Ways to Add Parentheses)
// @Author: 15816537946@163.com
// @Date: 2019-11-18 17:48:43
// @Runtime: 0 ms
// @Memory: 2.1 MB

func diffWaysToCompute(input string) []int {
	cache := make(map[string][]int)
	var dfs func(string) []int
	dfs = func(s string) []int {
		res := make([]int, 0, len(s))
		if t, ok := cache[s]; ok {
			return t
		}

		for i := range s {
			if s[i] == '+' || s[i] == '-' || s[i] == '*' {
				// 此时,s[i] 作为最后一个运算的运算符
				for _, left := range dfs(s[:i]) {
					for _, right := range dfs(s[i+1:]) {
						res = append(res, operate(left, right, s[i]))
					}
				}
			}
		}

		// s 中不存在运算符
		if len(res) == 0 {
			temp, _ := strconv.Atoi(s)
			res = append(res, temp)
		}

		cache[s] = res
		return res
	}

	return dfs(input)
}

func operate(a, b int, opt byte) int {
	switch opt {
	case '+':
		return a + b
	case '-':
		return a - b
	default:
		return a * b
	}
}