题目链接
https://leetcode.com/problems/different-ways-to-add-parentheses/
描述
Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, - and *.
Example 1:
Input: “2-1-1”
Output: [0, 2]
Explanation:
((2-1)-1) = 0
(2-(1-1)) = 2
Example 2:
Input: “23-45”
Output: [-34, -14, -10, -10, 10]
Explanation:
(2*(3-(45))) = -34
((23)-(45)) = -14
((2(3-4))5) = -10
(2((3-4)5)) = -10
(((23)-4)*5) = 10
解题思路
自顶向下,分而治之进行递归,如果遇到(+,-,*)任何符号则将字符串一分为二,分别计算左边可以产生的结果和右边产生的结果,然后将结果做笛卡尔乘积,向上层返回结果。
示例代码(第一次使用golang刷题)
func diffWaysToCompute(input string) []int {
res := []int{}
flag := true
for i := 0; i < len(input); i++ {
if input[i] == '+' ||
input[i] == '-' ||
input[i] == '*' {
flag = false
leftpart := diffWaysToCompute(input[0:i])
rightpart := diffWaysToCompute(input[i+1:])
for _,left := range leftpart {
for _,right := range rightpart {
if input[i] == '+' {
tmp := left + right
res = append(res,tmp)
} else if input[i] == '-' {
tmp := left - right
res = append(res,tmp)
} else if input[i] == '*' {
tmp := left * right
res = append(res,tmp)
}
}
}
}
}
if flag {
i, err := strconv.Atoi(input)
if err != nil {
panic("err number!")
}
res = append(res, i)
}
return res
}
单元测试
import (
"fmt"
"testing"
)
func TestDiffWaysToCompute(t *testing.T) {
res := diffWaysToCompute("2*3-4*5")
fmt.Printf("res : %v",res)
if len(res) != 5 {
t.Errorf("err res: %v",res)
}
}