241. Different Ways to Add Parentheses
Medium
3696184Add to ListShare
Given a string expression of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. You may return the answer in any order.
Example 1:
Input: expression = "2-1-1" Output: [0,2] Explanation: ((2-1)-1) = 0 (2-(1-1)) = 2
Example 2:
Input: expression = "2*3-4*5" Output: [-34,-14,-10,-10,10] Explanation: (2*(3-(4*5))) = -34 ((2*3)-(4*5)) = -14 ((2*(3-4))*5) = -10 (2*((3-4)*5)) = -10 (((2*3)-4)*5) = 10
Constraints:
1 <= expression.length <= 20expressionconsists of digits and the operator'+','-', and'*'.- All the integer values in the input expression are in the range
[0, 99].
class Solution:
def diffWaysToCompute(self, expression: str) -> List[int]:
"""
assert sorted(Solution().diffWaysToCompute("2-1-1")) == [0, 2]
assert sorted(Solution().diffWaysToCompute("2")) == [2]
assert sorted(Solution().diffWaysToCompute("2*3-4*5")) == [-34, -14, -10, -10, 10]
参考别人的解法:对符号两端的表达式分治,求出左右两边各种情况,进行组合
"""
def diffWaysToCompute0(expression: str) -> List[int]:
if dp.get(expression) is not None:
return dp[expression]
result = []
for i in range(len(expression)):
c = expression[i]
if c == "+" or c == "-" or c == "*":
left = diffWaysToCompute0(expression[0:i])
right = diffWaysToCompute0(expression[i + 1:])
# 这里二重循环为左右两边各种情况的组合
for num1 in left:
for num2 in right:
if c == "+":
result.append(num1 + num2)
if c == "-":
result.append(num1 - num2)
if c == "*":
result.append(num1 * num2)
if len(result) == 0:
result.append(int(expression))
# print(expression + ":" + str(result))
dp[expression] = result
return result
dp = {}
return diffWaysToCompute0(expression)
本文介绍了一种算法,如何计算字符串形式的数学表达式中不同括号组合方式的所有可能结果。通过递归和动态规划的方法,解决从'2-1-1'到'2*3-4*5'这类问题,返回包括0、2、-34等在内的所有合法结果。
237

被折叠的 条评论
为什么被折叠?



