当前位置:网站首页>leetcode:437. 路径总和 III【dfs 选还是不选?】
leetcode:437. 路径总和 III【dfs 选还是不选?】
2022-04-23 12:34:00 【白速龙王的回眸】


分析
思路很清晰
选不选当前的
选当前的带着和进入左右孩子
不选当前的直接进入左右孩子
选的话直接内层dfs搞定
不选的话外层调用self
得到一个以每个节点作为start
然后都选当前的一个判断
ac code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:
def dfs(root, targetSum):
if not root:
return 0
ret = 0
if root.val == targetSum:
ret += 1
# 选了当前root的
ret += dfs(root.left, targetSum - root.val)
ret += dfs(root.right, targetSum - root.val)
return ret
if not root:
return 0
ret = dfs(root, targetSum)
# 不选当前root
ret += self.pathSum(root.left, targetSum)
ret += self.pathSum(root.right, targetSum)
return ret
总结
选当前的就进入dfs,然后判断none,如果刚好等就+1
否则选了当前进入下一层dfs
若不选当前直接在外面进入pathSum,无视掉root.val的值即可
这里就是一个经典的 选当前再遍历左右 or 不选当前就遍历左后
版权声明
本文为[白速龙王的回眸]所创,转载请带上原文链接,感谢
https://bridge-killer.blog.csdn.net/article/details/124361556
边栏推荐
猜你喜欢
随机推荐
Fabric 1.0 source code analysis (33) implementation of peer channel command and subcommand
How do traditional enterprises cope with digital transformation? These books give you the answer
How to expand the capacity of the server in the 100 million level traffic architecture? Well written!
31岁才转行程序员,目前34了,我来说说我的经历和一些感受吧...
消息队列概述
In idea Solution to the problem of garbled code in Chinese display of properties file
异步时钟亚稳态 的解决方案——多bit信号
The database navigator uses the default MySQL connection prompt: the server time zone value 'Ö Ð¹ ú±ê ×¼ ʱ ¼ ä’ is unrecognized or repres
Windows2008系统如何切换PHP版本
对称加密、证书加密
QT redraw events and cuts
BUUCTF WEB [BJDCTF2020]The mystery of ip
Next. JS static data generation and server-side rendering
BUUCTF WEB [BJDCTF2020]ZJCTF,不过如此
Idea code formatting plug-in save actions
Running error: unable to find or load the main class com xxx. Application
uni-app 原生APP-云打包集成极光推送(JG-JPUSH)详细教程
程序员如何用130行代码敲定核酸统计
Number of nodes of complete binary tree
Source code analysis of synchronousqueue







