题解 | #给表达式添加运算符#

给表达式添加运算符

http://www.nowcoder.com/practice/fdaee292bdaf4a7eb686c8ce72b2f3e1

dfs, 给每个数字添加一个运算符,直到数字字符串结尾,比较计算结果和目标值是否相同

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param num string字符串 
# @param target int整型 
# @return string字符串一维数组
#
class Solution:
    def addOpt(self , num: str, target: int) -> List[str]:
        # write code here
        res = set()
        def dfs(idx, path, t):
            nonlocal res
            if idx > len(num):
                return
            if idx == len(num) and t == target:
                res.add(path)
                return
            for i in range(idx, len(num)):
                dfs(i + 1, path + "+" + num[i], t + int(num[i]))
                dfs(i + 1, path + "-" + num[i], t - int(num[i]))
                dfs(i + 1, path + "*" + num[i], t * int(num[i]))
        if len(num) == 1:
            if int(num) == target:
                return [num]
        else:
            dfs(1, num[0], int(num[0]))
            return list(res)
                
全部评论
"123",7 这个咋说
点赞 回复 分享
发布于 2023-04-04 10:21 北京

相关推荐

评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务