1. 程式人生 > >LeetCode: Expression Add Operators

LeetCode: Expression Add Operators

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.

考慮需要回溯的情形:連乘使得乘法運算的結果不能立刻更新到加和結果上,數字組合成為新數時需要記錄計算過程中的最後一個數。共計有兩個需要回溯或者記錄的量:乘法結果和上一個數

class Solution:
    def
addOperators(self, num, target):
""" :type num: str :type target: int :rtype: List[str] """ if not num: return [] digit = list(map(int,num)) result = list() def helper(i,expr,prod,prevSum,cur): if i == len(num)-1
: if prevSum + prod + digit[i] == target: result.append(expr+'+'+num[i]) if prevSum + prod - digit[i] == target: result.append(expr+'-'+num[i]) if prevSum + prod*digit[i] == target: result.append(expr+'*'
+num[i]) if cur !=0 and prevSum + prod*10+prod/cur*digit[i] == target: result.append(expr+num[i]) else: helper(i+1,expr+'+'+num[i],digit[i],prevSum+prod,digit[i]) helper(i+1,expr+'-'+num[i],-digit[i],prevSum+prod,digit[i]) helper(i+1,expr+'*'+num[i],prod*digit[i],prevSum,digit[i]) if cur!=0: helper(i+1,expr+num[i],prod*10+prod/cur*digit[i],prevSum,cur*10+digit[i]) helper(1,num[0],digit[0],0,digit[0]) return result