Skip to content

Commit 88f2d24

Browse files
committed
Solve 241 with python(dp)
1 parent bcb0363 commit 88f2d24

File tree

1 file changed

+34
-0
lines changed
  • solutions/241.Different_Ways_to_Add_Parentheses

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#!/usr/bin/python3
2+
# -*- coding: utf-8 -*-
3+
# Author: illuz <iilluzen[at]gmail.com>
4+
# File: AC_dp_n2.py
5+
# Create Date: 2015-10-23 14:38:55
6+
# Usage: AC_dp_n2.py
7+
# Descripton:
8+
9+
class Solution(object):
10+
def diffWaysToCompute(self, input):
11+
"""
12+
:type input: str
13+
:rtype: List[int]
14+
"""
15+
return self.helper(input, {})
16+
17+
def helper(self, input, seen):
18+
if input in seen:
19+
return seen[input]
20+
if input.isnumeric():
21+
return [int(input)]
22+
res = []
23+
for i, c in enumerate(input):
24+
if c in '-+*':
25+
L = self.helper(input[:i], seen)
26+
R = self.helper(input[i+1:], seen)
27+
res += [l+r if c == '+' else l-r if c == '-' else l*r
28+
for l in L
29+
for r in R]
30+
seen[input] = res
31+
return res
32+
33+
s = Solution()
34+
print(s.diffWaysToCompute('2*3+4*5'))

0 commit comments

Comments
 (0)