当前位置:网站首页>241. 为运算表达式设计优先级
241. 为运算表达式设计优先级
2022-07-01 03:23:00 【Sun_Sky_Sea】
241. 为运算表达式设计优先级
原始题目链接:https://leetcode.cn/problems/different-ways-to-add-parentheses/
给你一个由数字和运算符组成的字符串 expression ,按不同优先级组合数字和运算符,计算并返回所有可能组合的结果。你可以 按任意顺序 返回答案。
示例 1:
输入:expression = “2-1-1”
输出:[0,2]
解释:
((2-1)-1) = 0
(2-(1-1)) = 2
示例 2:
输入:expression = “23-45”
输出:[-34,-14,-10,-10,10]
解释:
(2*(3-(45))) = -34
((23)-(45)) = -14
((2(3-4))5) = -10
(2((3-4)5)) = -10
(((23)-4)*5) = 10
提示:
1 <= expression.length <= 20
expression 由数字和算符 ‘+’、‘-’ 和 ‘*’ 组成。
输入表达式中的所有整数值在范围 [0, 99]
解题思路:
分治算法,以运算符为界限,分成左右两边子表达式,再继续分,直到是数字(递归结束标志),再判断运算符进行合并。
代码实现:
class Solution:
def diffWaysToCompute(self, expression: str) -> List[int]:
# 递归结束标志:只有数字,直接返回数字
if expression.isdigit():
return [int(expression)]
ans = []
for i, c in enumerate(expression):
# 遇到运算符就拆分,分别计算左右两侧的子表达式的值
if c in "+-*":
left = self.diffWaysToCompute(expression[:i])
right = self.diffWaysToCompute(expression[i + 1:])
# 合并拆分子表达式的值
for l in left:
for r in right:
if c == '+':
ans.append(l + r)
if c == '-':
ans.append(l - r)
if c == '*':
ans.append(l * r)
return ans
参考文献:
https://leetcode.cn/problems/different-ways-to-add-parentheses/solution/pythongolang-fen-zhi-suan-fa-by-jalan/
边栏推荐
- leetcode 1818 绝对值,排序,二分法,最大值
- 【伸手党福利】开发人员重装系统顺序
- Test function in pychram
- [nine day training] content III of the problem solution of leetcode question brushing Report
- Addition without addition, subtraction, multiplication and division
- 排序链表(归并排序)
- 10、Scanner.next() 无法读取空格/indexOf -1
- The value of the second servo encoder is linked to the NC virtual axis of Beifu PLC for display
- 用小程序的技术优势发展产业互联网
- Edge drawing: a combined real-time edge and segment detector
猜你喜欢

Research on target recognition and tracking based on 3D laser point cloud

后台系统右边内容如何出现滚动条和解决双滚动条的问题

C # realize solving the shortest path of unauthorized graph based on breadth first BFS -- complete program display

idea插件备份表

Random seed torch in deep learning manual_ seed(number)、torch. cuda. manual_ seed(number)

Detailed list of errors related to twincat3 ads of Beifu

在线公网安备案保姆级教程【伸手党福利】

The method to measure the similarity of two vectors: cosine similarity, pytorch calculate cosine similarity: torch nn. CosineSimilarity(dim=1, eps=1e-08)

Data exchange JSON

Gorilla/mux framework (RK boot): RPC error code design
随机推荐
Error: plug ins declaring extensions or extension points must set the singleton directive to true
Introduction to EtherCAT
【伸手党福利】JSONObject转String保留空字段
SEM of C language_ Tvariable type
LeetCode 144二叉树的前序遍历、LeetCode 114二叉树展开为链表
FCN全卷积网络理解及代码实现(来自pytorch官方实现)
LeetCode 128最长连续序列(哈希set)
[daily training] 1175 Prime permutation
Asgnet paper and code interpretation 2
[深度学习]激活函数(Sigmoid等)、前向传播、反向传播和梯度优化;optimizer.zero_grad(), loss.backward(), optimizer.step()的作用及原理
排序链表(归并排序)
Promise中finally的用法
Finally in promise
实现pow(x,n)函数
bootsrap中的栅格系统
RSN:Learning to Exploit Long-term Relational Dependencies in Knowledge Graphs
The method to measure the similarity of two vectors: cosine similarity, pytorch calculate cosine similarity: torch nn. CosineSimilarity(dim=1, eps=1e-08)
Go tool cli for command line implementation
Valid brackets (force deduction 20)
Detailed explanation of ES6 deconstruction grammar