LeetCode 0241. Different Ways to Add Parentheses爲運算表達式設計優先級【Medium】【Python】【分治】
LeetCodepython
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 *
.git
Example 1:github
Input: "2-1-1" Output: [0, 2] Explanation: ((2-1)-1) = 0 (2-(1-1)) = 2
Example 2:app
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
力扣ide
給定一個含有數字和運算符的字符串,爲表達式添加括號,改變其運算優先級以求出不一樣的結果。你須要給出全部可能的組合的結果。有效的運算符號包含 +
, -
和 *
。設計
示例 1:code
輸入: "2-1-1" 輸出: [0, 2] 解釋: ((2-1)-1) = 0 (2-(1-1)) = 2
示例 2:leetcode
輸入: "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)get
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