Backtrack
282. Expression Add Operator
Input: num = "123", target = 6
Output: ["1+2+3", "1*2*3"] 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)351. Android Unlock Pattern
Last updated