leetcode--Different Ways to Add Parentheses
题目链接:https://leetcode.com/submissions/detail/86532557/
算法类型:分治法
题目分析:计算表达式的所有结果可能性
代码实现:
1 class Solution(object): 2 def diffWaysToCompute(self, input): 3 """ 4 :type input: str 5 :rtype: List[int] 6 """ 7 def dfs(s, cache) : 8 ops = {'+':lambda x,y:x+y, '-':lambda x,y:x-y, '*':lambda x,y:x*y} 9 if not cache.has_key(s) : 10 ret = [] 11 for k, v in enumerate(s) : 12 if v in '+-*' : 13 for left in dfs(s[:k], cache) : 14 for right in dfs(s[k+1:], cache) : 15 ret.append(ops[v](left,right)) 16 if not ret : 17 ret.append(int(s)) 18 cache[s] = ret 19 return cache[s] 20 21 return dfs(input, {})