241. Different Ways to Add Parentheses

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 <= 20
  • expression consists 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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值