给定一个仅包含数字 0-9 的字符串 num 和一个目标值整数 target ,在 num 的数字之间添加 二元 运算符(不是一元)+、- 或 * ,返回所有能够得到目标值的表达式。
示例 1:
输入: num = "123", target = 6
输出: ["1+2+3", "1*2*3"]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/expression-add-operators
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
遍历所有的数字和运算符组合 保留值满足要求的
class Solution(object):
res = []
def addOperators(self, num, target):
"""
:type num: str
:type target: int
:rtype: List[str]
"""
self.res = []
self.deep1(0, num, target, 0, 0, "")
return self.res
def deep1(self, index, num, target, res, last_incr, path):
if index >= len(num):
if res == target:
self.res.append(path)
return
for i in range(index, len(num)):
if num[index:index+1] == '0' and i > index:
break
new_num = eval(num[index:i+1])
if index == 0:
self.deep1(i + 1, num, target, new_num, new_num, str(new_num))
continue
self.deep1(i + 1, num, target, res - last_incr + last_incr * new_num , last_incr * new_num, path + "*" + str(new_num))
self.deep1(i + 1, num, target, res - new_num , -new_num, path + "-" + str(new_num))
self.deep1(i + 1, num, target, res + new_num , new_num, path + "+" + str(new_num))
def deep(self, index, num, target):
pass