leetcode -- Expression Add Operators --难点再看

本文详细解读了LeetCode中关于在数字字符串中添加运算符以达到目标值的问题,通过深度优先搜索(DFS)算法进行求解。包括参数解释、递归过程以及特殊情况处理,同时提供了代码实现和相关链接资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://leetcode.com/problems/expression-add-operators/

主要参考https://leetcode.com/discuss/70597/clean-python-dfs-with-comments
其余参考都看不大懂。

这里
dfs() parameters:
num: remaining num string
temp: temporally string with operators added
cur: current result of “temp” string
last: last multiply-level number in “temp”. if next operator is “multiply”, “cur” and “last” will be updated。比如说temp = A+B, last = B; temp = A - B, last = -B; temp = A*B, last = A*B; temp = A+B*C, last = B*C.
res: result to return

思路就是枚举第一个操作数,然后在dfs里再枚举第二个操作数,然后在第一和第二个操作数中间枚举+-*.见code以及下面的图片

解释各种变量

解释如何dfs

对于上图第三点,我们要注意一个特殊情况,如果temp = A*B, 那么last = A*B, cur = A*B, 那么依旧是cur - last + last * int(val), 或者cur - old_last + new_last.

class Solution(object):
    def addOperators(self, num, target):
        res, self.target = [], target
        for i in range(1,len(num)+1):
            if i == 1 or (i > 1 and num[0] != "0"): # prevent "00*" as a number
                self.dfs(num[i:], num[:i], int(num[:i]), int(num[:i]), res) # this step put first number in the string
        return res

    def dfs(self, num, temp, cur, last, res):
        if not num:
            if cur == self.target:
                res.append(temp)
            return
        for i in range(1, len(num)+1):
            val = num[:i]
            if i == 1 or (i > 1 and num[0] != "0"): # prevent "00*" as a number
                #注意这里是在temp和val中加操作符
                self.dfs(num[i:], temp + "+" + val, cur+int(val), int(val), res)
                self.dfs(num[i:], temp + "-" + val, cur-int(val), -int(val), res)
                old_last = last
                new_last = last*int(val)
                self.dfs(num[i:], temp + "*" + val, cur-old_last+new_last, new_last, res)

参考:
http://bookshadow.com/weblog/2015/09/16/leetcode-expression-add-operators/

http://www.cnblogs.com/grandyang/p/4814506.html

http://blog.youkuaiyun.com/er_plough/article/details/48624117

http://nb4799.neu.edu/wordpress/?p=731

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值