LeetCode | 0241. 为运算表达式设计优先级【Python】

LeetCode 0241. Different Ways to Add Parentheses为运算表达式设计优先级【Medium】【Python】【分治】

Problem

LeetCode

Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, - and *.

Example 1:

Input: "2-1-1"
Output: [0, 2]
Explanation: 
((2-1)-1) = 0 
(2-(1-1)) = 2

Example 2:

Input: "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

问题

力扣

给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, -*

示例 1:

输入: "2-1-1"
输出: [0, 2]
解释: 
((2-1)-1) = 0 
(2-(1-1)) = 2

示例 2:

输入: "2*3-4*5"
输出: [-34, -14, -10, -10, 10]
解释: 
(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

思路

分治

循环遍历,如果当前位置是运算符,那么分别计算左右两边的式子的值,然后用运算符拼接在一起。

时间复杂度: O(n)

Python3代码

class Solution:
    def diffWaysToCompute(self, input: str) -> List[int]:
        # solution: Divide and conquer
        if input.isdigit():  # input only contains digital
            return [int(input)]
        n = len(input)
        res = []
        for i in range(n):
            if input[i] in '+-*':
                lefts = self.diffWaysToCompute(input[:i])
                rights = self.diffWaysToCompute(input[i+1:])
                for left in lefts:
                    for right in rights:
                        if input[i] == '+':
                            res.append(left + right)
                        elif input[i] == '-':
                            res.append(left - right)
                        elif input[i] == '*':
                            res.append(left * right)
                        # # use eval
                        # res.append(eval(str(left) + input[i] + str(right)))
        return res

代码地址

GitHub链接

LeetCode个人题解 文章被收录于专栏

LeetCode个人题解,目前主要是 Python3 题解。

全部评论

相关推荐

叶扰云倾:进度更新,现在阿里云面完3面了,感觉3面答得还行,基本都答上了,自己熟悉的地方也说的比较细致,但感觉面试官有点心不在焉不知道是不是不想要我了,求阿里收留,我直接秒到岗当阿里孝子,学校那边的房子都退租了,下学期都不回学校,全职猛猛实习半年。这种条件还不诱人吗难道 然后现在约到了字节的一面和淘天的复活赛,外加猿辅导。华为笔试完没动静。 美团那边之前投了个base广州的,把我流程卡麻了,应该是不怎么招人,我直接简历挂了,现在进了一个正常的后端流程,还在筛选,不知道还有没有hc。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务