难度:中等
题目描述:
思路总结:借用大神思路,分治法,具体逻辑不明白的,找个公式手推一下就理解了。思路和代码都及其简单。
知识点:Python装饰器讲解大全
题解一:(分治法)
class Solution:
def diffWaysToCompute(self, input: str) -> List[int]:
#思路:分治法看不懂的建议5*2+3-4手推一遍
if input.isdigit():return [int(input)]
res = []
for i in range(len(input)):
if input[i] in ["-", "+", "*"]:
left = self.diffWaysToCompute(input[:i])
right = self.diffWaysToCompute(input[i+1:])
for l in left:
for r in right:
res.append(self.helper(int(l), int(r), input[i]))
return res
def helper(self,i,j,op):
if op == "-":
return i - j
elif op == "+":
return i + j
else:
return i * j
题解一改进:(加了个lru_cache装饰器)
import functools
class Solution:
@functools.lru_cache()
def diffWaysToCompute(self, input: str) -> List[int]: