241. Different Ways to Add Parentheses
Idea
- This algorithm divides
inp
string by operators.- each operator is a dividing point, so reculsively call all possible cases.
1 2 3 4 5
for i in range(len(inp)): if not self.match(inp[i]): continue left = self.diffWaysToCompute(inp[:i]) right = self.diffWaysToCompute(inp[i+1:])
- each operator is a dividing point, so reculsively call all possible cases.
- From reculsive calling, If we get the
left
andright
results, merge the results.- all possible combinataions are generated.
1 2 3 4 5 6
for i in range(len(inp)): ... operator = inp[i] for l in left: for r in right: res.append(self.op(operator, l, r))
- all possible combinataions are generated.
- Base cases can be occured when
left
orright
are empty.1 2
if not bool(res): return [int(inp)]
In [1]:
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
class Solution(object):
def __init__(self):
self.match = lambda c: True if c in ['+', '-', '*'] else False
def op(self, o, a, b):
if o == '+':
return a + b
elif o == '-':
return a - b
elif o == '*':
return a * b
assert o, 'invalid'
def diffWaysToCompute(self, inp):
"""
:type inp: str
:rtype: List[int]
"""
res = []
for i in range(len(inp)):
if not self.match(inp[i]):
continue
left = self.diffWaysToCompute(inp[:i])
right = self.diffWaysToCompute(inp[i+1:])
operator = inp[i]
for l in left:
for r in right:
res.append(self.op(operator, l, r))
if not bool(res):
return [int(inp)]
return sorted(res)
In [2]:
1
2
3
inp = "2*3-4*5"
sol = Solution()
sol.diffWaysToCompute(inp)
1
[-34, -14, -10, -10, 10]
Leave a comment