66 lines
1.3 KiB
Go
66 lines
1.3 KiB
Go
package main
|
|
|
|
import (
|
|
"unicode"
|
|
)
|
|
|
|
func diffWaysToCompute(expression string) []int {
|
|
n := len(expression)
|
|
dp := make([][][]int, n)
|
|
for i := range dp {
|
|
dp[i] = make([][]int, n)
|
|
}
|
|
|
|
computeBase := func() {
|
|
for i, c := range expression {
|
|
if !unicode.IsDigit(c) {
|
|
continue
|
|
}
|
|
|
|
digit := int(c - '0')
|
|
dp[i][i] = append(dp[i][i], digit)
|
|
|
|
if i+1 < n && unicode.IsDigit(rune(expression[i+1])) {
|
|
nextDigit := int(expression[i+1] - '0')
|
|
dp[i][i+1] = append(dp[i][i+1], digit*10+nextDigit)
|
|
}
|
|
}
|
|
}
|
|
computeBase()
|
|
|
|
precompute := func(op byte, left, right, results []int) []int {
|
|
for _, l := range left {
|
|
for _, r := range right {
|
|
switch op {
|
|
case '+':
|
|
results = append(results, l+r)
|
|
case '-':
|
|
results = append(results, l-r)
|
|
case '*':
|
|
results = append(results, l*r)
|
|
}
|
|
}
|
|
}
|
|
|
|
return results
|
|
}
|
|
computeSubexpression := func(l, r int) {
|
|
for mid := l; mid <= r; mid++ {
|
|
if unicode.IsDigit(rune(expression[mid])) {
|
|
continue
|
|
}
|
|
|
|
left, right := dp[l][mid-1], dp[mid+1][r]
|
|
dp[l][r] = precompute(expression[mid], left, right, dp[l][r])
|
|
}
|
|
}
|
|
|
|
for length := 3; length <= n; length++ {
|
|
for l := 0; l+length-1 < n; l++ {
|
|
r := l + length - 1
|
|
computeSubexpression(l, r)
|
|
}
|
|
}
|
|
|
|
return dp[0][n-1]
|
|
}
|