题目链接:https://leetcode.com/submissions/detail/86532557/
算法类型:分治法
题目分析:计算表达式的所有结果可能性
代码实现:
class Solution(object):
def diffWaysToCompute(self, input):
"""
:type input: str
:rtype: List[int]
"""
def dfs(s, cache) :
ops = {'+':lambda x,y:x+y, '-':lambda x,y:x-y, '*':lambda x,y:x*y}
if not cache.has_key(s) :
ret = []
for k, v in enumerate(s) :
if v in '+-*' :
for left in dfs(s[:k], cache) :
for right in dfs(s[k+1:], cache) :
ret.append(ops[v](left,right))
if not ret :
ret.append(int(s))
cache[s] = ret
return cache[s] return dfs(input, {})