https://leetcode.com/problems/expression-add-operators/
主要参考https://leetcode.com/discuss/70597/clean-python-dfs-with-comments
其余参考都看不大懂。
这里
dfs() parameters:
num: remaining num string
temp: temporally string with operators added
cur: current result of “temp” string
last: last multiply-level number in “temp”. if next operator is “multiply”, “cur” and “last” will be updated。比如说temp = A+B, last = B; temp = A - B, last = -B; temp = A*B, last = A*B; temp = A+B*C, last = B*C.
res: result to return
思路就是枚举第一个操作数,然后在dfs里再枚举第二个操作数,然后在第一和第二个操作数中间枚举+-*.见code以及下面的图片
对于上图第三点,我们要注意一个特殊情况,如果temp = A*B, 那么last = A*B, cur = A*B, 那么依旧是cur - last + last * int(val), 或者cur - old_last + new_last.
class Solution(object):
def addOperators(self, num, target):
res, self.target = [], target
for i in range(1,len(num)+1):
if i == 1 or (i > 1 and num[0] != "0"): # prevent "00*" as a number
self.dfs(num[i:], num[:i], int(num[:i]), int(num[:i]), res) # this step put first number in the string
return res
def dfs(self, num, temp, cur, last, res):
if not num:
if cur == self.target:
res.append(temp)
return
for i in range(1, len(num)+1):
val = num[:i]
if i == 1 or (i > 1 and num[0] != "0"): # prevent "00*" as a number
#注意这里是在temp和val中加操作符
self.dfs(num[i:], temp + "+" + val, cur+int(val), int(val), res)
self.dfs(num[i:], temp + "-" + val, cur-int(val), -int(val), res)
old_last = last
new_last = last*int(val)
self.dfs(num[i:], temp + "*" + val, cur-old_last+new_last, new_last, res)
参考:
http://bookshadow.com/weblog/2015/09/16/leetcode-expression-add-operators/
http://www.cnblogs.com/grandyang/p/4814506.html
http://blog.youkuaiyun.com/er_plough/article/details/48624117