LeetCode 282. [Python] Expression Add Operators
原题链接
困难
作者:
徐辰潇
,
2020-04-12 04:25:13
,
所有人可见
,
阅读 797
class Solution:
def addOperators(self, num: str, target: int) -> List[str]:
#TC: O(N * 4^N)
#SC: O(N)
res = []
def helper(index, accum, candi, prev):
if index == len(num):
if accum == target:
res.append(candi[1:])
return
for i in range(index, len(num)):
val = int(num[index:i+1])
helper(i+1, accum + val, candi + '+' + str(val), val)
if index > 0:
helper(i+1, accum - val, candi + '-' + str(val), -val)
helper(i+1, accum - prev + prev*val, candi + '*' + str(val), prev*val)
if int(num[index]) == 0:
break
helper(0, 0, "", 0)
return res