当前位置:网站首页>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板子题
如何想到那三个状态呢?望洋兴叹!
边栏推荐
- 如何获取GC(垃圾回收器)的STW(暂停)时间?
- 有關二叉樹的一些練習題
- Source insight 工具安装及使用方法
- 【系统设计】邻近服务
- 手把手带你玩摄像头模组
- Reading and writing Apache poi
- Markem imaje马肯依玛士喷码机维修9450E打码机维修
- Improving efficiency or increasing costs, how should developers understand pair programming?
- How do I get the STW (pause) time of a GC (garbage collector)?
- 运维一线工作常用shell脚本再整理
猜你喜欢

Preliminary understanding of pytorch
Shortcut key bug, reproducible (it seems that bug is the required function [funny.Gif])

NoSQL database redis installation

Improving efficiency or increasing costs, how should developers understand pair programming?

prometheus告警流程及相关时间参数说明

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

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

Take you to play with the camera module

HiTek电源维修X光机高压发生器维修XR150-603-02

Installation and usage of source insight tool
随机推荐
Quartz(定时器)
QT运行显示 This application failed to start because it could not find or load the Qt platform plugin
Reading and writing Apache poi
R语言使用econocharts包创建微观经济或宏观经济图、demand函数可视化需求曲线(demand curve)、自定义配置demand函数的参数丰富可视化效果
JS 文件上传下载
ucore lab4
[system design] proximity service
快速入门CherryPy(1)
Preliminary understanding of pytorch
I'm almost addicted to it. I can't sleep! Let a bug fuck me twice!
C # solve the relative path problem using SQLite
fastadmin 安装后访问后台提示模块不存在
巴基斯坦安全部队开展反恐行动 打死7名恐怖分子
ucore lab3
Conception de plusieurs classes
Obsidian 一周使用心得(配置、主题和插件)
Pakistani security forces killed 7 terrorists in anti-terrorism operation
微信小程序学习之五种页面跳转方法.
Design of multiple classes
unity--newtonsoft. JSON parsing