Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, -and *.
Example 1:
Input:"2-1-1"Output:[0, 2]Explanation: ((2-1)-1) = 0 (2-(1-1)) = 2
Example 2:
Input:"2*3-4*5"Output:[-34, -14, -10, -10, 10]Explanation: (2*(3-(4*5))) = -34 ((2*3)-(4*5)) = -14 ((2*(3-4))*5) = -10 (2*((3-4)*5)) = -10 (((2*3)-4)*5) = 10
这题标签是divide conquer,一开始没什么思路,看了一下花花酱的视频才明白怎么做。。。
关键就是按照operation符号来分割,然后分别递归。。。比如2*3-4*5,就是2 * 3-4*5,然后3-4*5又递归,就是3 - 4*5,如果ans长度为0,就返回int(input),此时Input就是一个数字,另外可以记住每次得到的子串表达式的值,减少运算量,但实际试下来,这样更慢。。不知道为啥。还有个技巧就是pyhton有定义运算function,分别是add,sup,mul,div这个一用舒服很多有没有!!!
from operator import *
class Solution(object):
def diffWaysToCompute(self, input):
"""
:type input: str
:rtype: List[int]
"""
dic={}
def helper(input):
# if input in dic:
# return dic[input]
op={"-":sub,"+":add,"*":mul,"/":div}
res=[]
for index,unit in enumerate(input):
if unit in op:
left=helper(input[:index])
right=helper(input[index+1:])
res.extend([op[unit](a,b) for a in left for b in right])
if len(res)==0:
return [int(input)]
else:
# dic[input]=res
return res
return helper(input)
637

被折叠的 条评论
为什么被折叠?



