当前位置:网站首页>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
边栏推荐
- Idea code formatting plug-in save actions
- Qt进程间通信
- S2-062 remote command execution vulnerability recurrence (cve-2021-31805)
- [unity note] basic lighting in l4unity
- 消息队列概述
- flask项目跨域拦截处理以及dbm数据库学习【包头文创网站开发】
- MySQL function - recursive function
- BUUCTF WEB [GXYCTF2019]禁止套娃
- CGC: contractual graph clustering for community detection and tracking
- Please help me see what this is, mysql5 5. Thanks
猜你喜欢
After a circle, I sorted out this set of interview questions..
在 VSCode 中调试 Jest 的测试用例,VSCode调试Jest测试用例报错basedir=$(dirname “$(echo “$0“ | sed -e ‘s,\\,/,g‘)“)解决
基于卷积神经网络的遥感影像分类识别系统
Qt进程间通信
On lambda powertools typescript
The database navigator uses the default MySQL connection prompt: the server time zone value 'Ö Ð¹ ú±ê ×¼ ʱ ¼ ä’ is unrecognized or repres
如何防止网站被黑客入侵篡改
标签与路径
How to expand the capacity of the server in the 100 million level traffic architecture? Well written!
Fastjson 2 来了,性能继续提升,还能再战十年
随机推荐
QT draw image
Intelligent multi line elastic cloud adds independent IP address. How to realize multi line function?
A graphic designer's fantasy world | ones characters
程序员如何用130行代码敲定核酸统计
Qt绘制图像
力扣刷题之完全二叉树的节点个数
BUUCTF WEB [BJDCTF2020]The mystery of ip
The maximum number of remote desktop servers has been exceeded
Web17——EL与JSTL的使用
Qt进程间通信
大家帮我看一下这是啥情况,MySQL5.5的。谢了
免费试用一个月的服务器,并附上教程
MySQL函数-递归函数
电脑系统卡如何解决?
Markdown grammar learning
【unity笔记】L4Unity中的基础光照
Introduction to metalama 4 Use fabric to manipulate items or namespaces
Here comes the detailed picture and text installation tutorial of H5 game
How to solve the computer system card?
IDEA 代码质量规范插件SonarLint