go: add «241. Different Ways to Add Parentheses»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-09-20 00:05:10 +02:00
parent 40da3403da
commit 9b3e3e9ee4
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,66 @@
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]
}