当前位置:网站首页>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
边栏推荐
- Lesson 26 static member functions of classes
- I changed to a programmer at the age of 31. Now I'm 34. Let me talk about my experience and some feelings
- 编程辅助工具推荐:图片工具snipaste
- CGC: contractual graph clustering for community detection and tracking
- NBIOT的AT指令
- 面了一圈,整理了这套面试题。。
- Analysis of InnoDB execution process in MySQL
- 第二十五课 类的静态成员变量
- Number of nodes of complete binary tree
- The maximum number of remote desktop servers has been exceeded
猜你喜欢
随机推荐
One way ANOVA of SPSS
flask项目跨域拦截处理以及dbm数据库学习【包头文创网站开发】
在 VSCode 中调试 Jest 的测试用例,VSCode调试Jest测试用例报错basedir=$(dirname “$(echo “$0“ | sed -e ‘s,\\,/,g‘)“)解决
worder字体网页字体对照表
Idea database navigator plug-in
关于使用Go语言创建WebSocket服务浅谈
STM32控制步进电机(ULN2003+28byj)
Plato Farm-以柏拉图为目标的农场元宇宙游戏
31岁才转行程序员,目前34了,我来说说我的经历和一些感受吧...
Outsourcing for five years, abandoned
What is a gateway
MySQL函数-递归函数
NBIOT的AT指令
BUUCTF WEB [BUUCTF 2018]Online Tool
解决disagrees about version of symbol device_create
Stacks and queues a
C set Logo Icon and shortcut icon
Lesson 26 static member functions of classes
QT draw image
Stm32cubeprogrammer basic instructions









