您的位置:首页 > 汽车 > 时评 > Golang | Leetcode Golang题解之第241题为运算表达式设计优先级

Golang | Leetcode Golang题解之第241题为运算表达式设计优先级

2024/11/18 9:37:37 来源:https://blog.csdn.net/weixin_66442839/article/details/140510835  浏览:    关键词:Golang | Leetcode Golang题解之第241题为运算表达式设计优先级

题目:

题解:

const addition, subtraction, multiplication = -1, -2, -3func diffWaysToCompute(expression string) []int {ops := []int{}for i, n := 0, len(expression); i < n; {if unicode.IsDigit(rune(expression[i])) {x := 0for ; i < n && unicode.IsDigit(rune(expression[i])); i++ {x = x*10 + int(expression[i]-'0')}ops = append(ops, x)} else {if expression[i] == '+' {ops = append(ops, addition)} else if expression[i] == '-' {ops = append(ops, subtraction)} else {ops = append(ops, multiplication)}i++}}n := len(ops)dp := make([][][]int, n)for i, x := range ops {dp[i] = make([][]int, n)dp[i][i] = []int{x}}for sz := 3; sz <= n; sz++ {for l, r := 0, sz-1; r < n; l += 2 {for k := l + 1; k < r; k += 2 {for _, x := range dp[l][k-1] {for _, y := range dp[k+1][r] {if ops[k] == addition {dp[l][r] = append(dp[l][r], x+y)} else if ops[k] == subtraction {dp[l][r] = append(dp[l][r], x-y)} else {dp[l][r] = append(dp[l][r], x*y)}}}}r += 2}}return dp[0][n-1]
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com