LeetCode | 0241. Different Ways to Add Parentheses爲運算表達式設計優先級【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鏈接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章