当前位置:网站首页>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
边栏推荐
猜你喜欢
随机推荐
How do programmers finalize nucleic acid statistics with 130 lines of code
CGC: contractual graph clustering for community detection and tracking
Source code analysis of synchronousqueue
Lesson 24 analysis of classical problems
Flash project cross domain interception and DBM database learning [Baotou cultural and creative website development]
【每日一题】棋盘问题
AI 视频云 VS 窄带高清,谁是视频时代的宠儿
Introduction to metalama 4 Use fabric to manipulate items or namespaces
航芯技术分享 | ACM32 MCU安全特性概述
传统企业如何应对数字化转型?这些书给你答案
Number of nodes of complete binary tree
Next. JS static data generation and server-side rendering
31岁才转行程序员,目前34了,我来说说我的经历和一些感受吧...
Lesson 23 temporary objects
uni-app 原生APP-云打包集成极光推送(JG-JPUSH)详细教程
网站首页文件被攻击篡改的形式有哪些
Intelligent multi line elastic cloud adds independent IP address. How to realize multi line function?
九十八、freemarker框架报错 s.e.ErrorMvcAutoConfiguration$StaticView : Cannot render error page for request
QT double buffer drawing
免费试用一个月的服务器,并附上教程









