Leetcode 241. Different Ways to Add Parentheses

Problem

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.

The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed 1 0 4 10^4 104.

Algorithm

Use the backtracking method to calculate all possible cases.

Code

class Solution:
    def diffWaysToCompute(self, expression: str) -> List[int]:
        nums, opts, val = [], [], 0
        for c in expression:
            if c >= '0' and c <= '9':
                val = val * 10 + ord(c) - ord('0')
            else:
                opts.append(c)
                nums.append(val)
                val = 0
        nums.append(val)

        def dfs(L, R):
            if L >= R:
                return [nums[R]]
            ans = []
            for i in range(L, R):
                val_L = dfs(L, i)
                val_R = dfs(i+1, R)
                for vl in val_L:
                    for vr in val_R:
                        if opts[i] == '+':
                            ans.append(vl + vr)
                        elif opts[i] == '-':
                            ans.append(vl - vr)
                        elif opts[i] == '*':
                            ans.append(vl * vr)
            return ans

        return dfs(0, len(opts))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值