当前位置:网站首页>leetcode:968. 监控二叉树【树状dp,维护每个节点子树的三个状态,非常难想权当学习,类比打家劫舍3】
leetcode:968. 监控二叉树【树状dp,维护每个节点子树的三个状态,非常难想权当学习,类比打家劫舍3】
2022-06-27 09:35:00 【白速龙王的回眸】

分析
三个状态,记录每个节点为根的子树:
状态 a:root 必须放置摄像头的情况下,覆盖整棵树需要的摄像头数目。
状态 b:覆盖整棵树需要的摄像头数目,无论 root 是否放置摄像头。
状态 c:覆盖两棵子树需要的摄像头数目,无论节点 root 本身是否被监控到。
a >= b >= c
a = lc + rc + 1
b = min(a, la + rb, ra + lb)
c = min(a, lb + rb)
式子1:当前根放了,只需覆盖两个子树就可以了(要求较低)
式子2:如果放了root就是a,如果不放那左右孩子至少有一个放,左放右随缘la + rb, 右放左随缘ra + lb
式子3:如果放了root就是a,如果不放,就是两个子树覆盖的的可能即可
如果是空的话,显然是不能选的,所以a填inf
ac code
class Solution:
def minCameraCover(self, root: TreeNode) -> int:
# 树状dp:三个状态(难以想象)
# 状态 a:root 必须放置摄像头的情况下,覆盖整棵树需要的摄像头数目。
# 状态 b:覆盖整棵树需要的摄像头数目,无论 root 是否放置摄像头。
# 状态 c:覆盖两棵子树需要的摄像头数目,无论节点 root 本身是否被监控到。
# a >= b >= c
def dfs(root: TreeNode) -> List[int]:
if not root:
return [float("inf"), 0, 0] # 不可能放,用inf
la, lb, lc = dfs(root.left)
ra, rb, rc = dfs(root.right)
a = lc + rc + 1
b = min(a, la + rb, ra + lb)
c = min(a, lb + rb)
#print(a, b, c)
return [a, b, c]
a, b, c = dfs(root)
return b
总结
树状dp板子题
如何想到那三个状态呢?望洋兴叹!
边栏推荐
- 初步认识pytorch
- Location and solution of network connection failure of primary online mobile terminal Report
- Some considerations on operation / method overloading for thread to release lock resources
- Scientists develop two new methods to provide stronger security protection for intelligent devices
- 内存泄露的最直接表现
- Shortcut key bug, reproducible (it seems that bug is the required function [funny.Gif])
- BufferedWriter 和 BufferedReader 的使用
- JS 文件上传下载
- Five page Jump methods for wechat applet learning
- 你睡觉时大脑真在自动学习!首个人体实验证据来了:加速1-4倍重放,深度睡眠阶段效果最好...
猜你喜欢

了解神经网络结构和优化方法

如何获取GC(垃圾回收器)的STW(暂停)时间?

Decompile the jar package and recompile it into a jar package after modification
![[MySQL basic] general syntax 1](/img/f2/fb38409c034546e503d08a0b96cc61.png)
[MySQL basic] general syntax 1

Quelques exercices sur les arbres binaires

IO pin configuration and pinctrl drive

Rman-08137 main library failed to delete archive file

【mysql篇-基础篇】通用语法1

反编译jar包,修改后重新编译为jar包

枚举?构造器?面试Demo
随机推荐
Process 0, process 1, process 2
Digital ic-1.9 understands the coding routine of state machine in communication protocol
Only one confirmcallback is supported by each rabbittemplate
[vivid understanding] the meanings of various evaluation indicators commonly used in deep learning TP, FP, TN, FN, IOU and accuracy
main()的参数argc与argv
巴基斯坦安全部队开展反恐行动 打死7名恐怖分子
TDengine 邀请函:做用技术改变世界的超级英雄,成为 TD Hero
E+H二次表维修PH变送器二次显示仪修理CPM253-MR0005
Freemarker
Reading and writing Apache poi
6月23日《Rust唠嗑室》第三期B站视频地址
10 常见网站安全攻击手段及防御方法
使用aspose-slides将ppt转pdf
std::memory_order_seq_cst内存序
Google browser chropath plug-in
快速入门CherryPy(1)
I'm almost addicted to it. I can't sleep! Let a bug fuck me twice!
最全H桥电机驱动模块L298N原理及应用
[diffusion model]
Shortcut key bug, reproducible (it seems that bug is the required function [funny.Gif])