边工作边刷题:70天一遍leetcode: day 41-1

Expression Add Operators

要点:难题,参考了https://discuss.leetcode.com/topic/30089/clean-python-dfs-with-comments。

  • 这里因为只有+、-、,没有(,),,所以实际上不从左向右的情况只有+/-遇到,并且只在相邻2位之间。所以这题不需要用stack。
  • 所以这里用diff表示上一步的变化以更新当前,用cur_sum记录上一步位置的局部解。遇到的时候,要去掉前面提前+/-的部分,所以是cur_sum-diff,而这个diff实际上就是前面+/-的第二个数,所以要diff当前数。当然还有abc的情况,假设在第二个,因为新的diff更新为ab,所以-diff+diffc实际上把前面的ab去掉了再用diff连乘。总之,diff就是到前一个+/-的整体值。
  • 00*的检测和Additive Number类似
  • 第一个数因为没有左边运算,所以在dfs之外处理

错误点

  • num是str所以num[0]!="0"
  • 中止条件是not num(num的[] check),错误的num==[]表示reference相同
  • 初始的cur_sum是第一个数,而不是0,因为实际每一位是每一个operator和其右边的数
class Solution(object):
    def addOperators(self, num, target):
        """
        :type num: str
        :type target: int
        :rtype: List[str]
        """
        def dfs(num, cur_sum, diff, target, res, solutions):
            # print res, cur_sum,target
            n = len(num)
            if not num: # error 2: num==[] means reference equal
                if cur_sum==target:
                    solutions.append(res)
                return
            
            for i in xrange(1, n+1):
                val=num[:i]
                if i==1 or num[0]!="0": # error 1: 
                    dfs(num[i:], cur_sum+int(val), int(val), target, res+"+"+num[:i], solutions)
                    dfs(num[i:], cur_sum-int(val), -int(val), target, res+"-"+num[:i], solutions)
                    dfs(num[i:], cur_sum-diff+diff*int(val), diff*int(val), target, res+"*"+num[:i], solutions)
        
        n = len(num)
        solutions = []
        for i in xrange(1, n+1):
            if i==1 or num[0]!="0":
                dfs(num[i:], int(num[:i]), int(num[:i]), target, num[:i], solutions)
        
        return solutions
原文地址:https://www.cnblogs.com/absolute/p/5690294.html