Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value.
Example 1:
Input: num = "123", target = 6
Output: ["1+2+3", "1*2*3"]
4 Operations: number extension, add, minus, multiple
Record pre number for multiple operator to rollback
First position only valid for add operator
Number init with '0' is invalid
def addOperators(self, num: str, target: int) -> List[str]:
self.ans = []
self.backtrack(num, '', target, 0, 0, 0)
return self.ans
def backtrack(self, num, express, target, idx, cur, pre):
if idx == len(num):
if cur == target:
self.ans.append(express)
return
for end in range(idx+1, len(num)+1):
# 01 is invalid
if num[idx] == '0' and end > idx+1: break
n = int(num[idx:end])
# first index just has positive number
if idx == 0:
self.backtrack(num, str(n), target, end, n, n)
else:
self.backtrack(num, express+'+'+str(n), target, end, cur+n, n)
self.backtrack(num, express+'-'+str(n), target, end, cur-n, -n)
self.backtrack(num, express+'*'+str(n), target, end, cur-pre+n*pre, n*pre)