-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdifferent_ways_to_add_parentheses_sol1.py
37 lines (32 loc) · 1.16 KB
/
different_ways_to_add_parentheses_sol1.py
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
33
34
35
36
37
class Solution(object):
def diffWaysToCompute(self, input):
"""
:type input: str
:rtype: List[int]
"""
memo = {}
def generate(input):
if len(input) == 1:
return [int(input)]
if input in memo:
return memo[input]
result = []
found = False
for i, c in enumerate(input):
if c == "+" or c == "-" or c == "*":
found = True
left = generate(input[:i])
right = generate(input[i+1:])
for l in left:
for r in right:
if c == "+":
result.append(l + r)
if c == "-":
result.append(l - r)
if c == "*":
result.append(l * r)
if not found:
result = [int(input)]
memo[input] = result
return result
return generate(input)