-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0241-different-ways-to-add-parentheses.py
More file actions
32 lines (28 loc) · 1.09 KB
/
0241-different-ways-to-add-parentheses.py
File metadata and controls
32 lines (28 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# time complexity: O(n*2^n)
# space complexity: O(2^n)
from typing import List
class Solution:
def diffWaysToCompute(self, expression: str) -> List[int]:
result = []
if len(expression) == 0:
return result
if len(expression) == 1:
return [int(expression)]
if len(expression) == 2 and expression[0].isdigit:
return [int(expression)]
for i, c in enumerate(expression):
if c.isdigit():
continue
leftResults = self.diffWaysToCompute(expression[:i])
rightResults = self.diffWaysToCompute(expression[i+1:])
for leftResult in leftResults:
for rightResult in rightResults:
if c == "+":
result.append(leftResult + rightResult)
elif c == "*":
result.append(leftResult * rightResult)
elif c == "-":
result.append(leftResult - rightResult)
return result
expression = "2-1-1"
print(Solution().diffWaysToCompute(expression))