LeetCode 0241. Different Ways to Add Parentheses為運算表達(dá)式設(shè)計優(yōu)先級【Medium】【Python】【分治】
Problem
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
問題
給定一個含有數(shù)字和運算符的字符串辙培,為表達(dá)式添加括號,改變其運算優(yōu)先級以求出不同的結(jié)果累驮。你需要給出所有可能的組合的結(jié)果勘高。有效的運算符號包含 +
, -
和 *
席爽。
示例 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
思路
分治
循環(huán)遍歷,如果當(dāng)前位置是運算符劫哼,那么分別計算左右兩邊的式子的值秒旋,然后用運算符拼接在一起。
時間復(fù)雜度: 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