leetcode 282. 给表达式添加运算符

给定一个仅包含数字 0-9 的字符串和一个目标值,在数字之间添加二元运算符(不是一元)+、- 或 * ,返回所有能够得到目标值的表达式。

示例 1:

输入: num = "123", target = 6
输出: ["1+2+3", "1*2*3"] 

示例 2:

输入: num = "232", target = 8
输出: ["2*3+2", "2+3*2"]

示例 3:

输入: num = "105", target = 5
输出: ["1*0+5","10-5"]
示例 4:
输入: num = "00", target = 0
输出: ["0+0", "0-0", "0*0"]
示例 5:
输入: num = "3456237490", target = 9191
输出: []
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution(object):
def addOperators(self, num, target):
def dfs(remain, curr_str, curr, prev):
if not remain and curr == target:
res.append(curr_str)

for i in range(1, len(remain) + 1):
if len(curr_str) == 0: #avoid generate str begin with +-*
if not (i > 1 and remain[0] == '0'): # avoid '0X' case be counted
dfs(remain[i:], remain[:i], int(remain[:i]), int(remain[:i]))
else:
if not (i > 1 and remain[0] == '0'):
dfs(remain[i:], curr_str + '+' + remain[:i], curr + int(remain[:i]), int(remain[:i]))
dfs(remain[i:], curr_str + '-' + remain[:i], curr - int(remain[:i]), -int(remain[:i]))
# need take extra care for '*' case, a+b*c = a+b-b+b*c
dfs(remain[i:], curr_str + '*' + remain[:i], curr - prev + prev * int(remain[:i]), prev * int(remain[:i]))

res = []
dfs(num, '', 0, 0)
return res
print(Solution().addOperators('105',5))