当前位置:网站首页>树形dp
树形dp
2022-07-04 06:13:00 【热心市民薛先生】


树形dp是二叉树形式的dp,本题要用个数组来保存当前节点的结果。
res[0] 表示不偷当前节点 res[1]表示偷当前节点
public int rob(TreeNode root) {
int[] res = recur(root);
return Math.max(res[0],res[1]);
}
public int[] recur(TreeNode root){
int []res = new int[2];
当前节点为空 返回
if(root == null) return res;
递归左右节点
int[] left = recur(root.left);
int[] right = recur(root.right);
不偷当前节点,可偷左右孩子节点
res[0] = Math.max(left[0],left[1]) + Math.max(right[0],right[1]);
偷当前节点,那么左右孩子节点不可偷,[0]代表不偷当前节点的值
res[1] = root.val + left[0] + right[0];
return res;
}
边栏推荐
- [microservice] Nacos cluster building and loading file configuration
- Notes and notes
- AWT common components, FileDialog file selection box
- BeanFactoryPostProcessor 与 BeanPostProcessor 相关子类概述
- 如何避免 JVM 内存泄漏?
- After the festival, a large number of people change careers. Is it still time to be 30? Listen to the experience of the past people
- Arcpy 利用updatelayer函数改变图层的符号系统
- Learning multi-level structural information for small organ segmentation
- AWT常用组件、FileDialog文件选择框
- px em rem的区别
猜你喜欢

冲击继电器JC-7/11/DC110V

ABAP:OOALV实现增删改查功能

一键过滤选择百度网盘文件

《ClickHouse原理解析与应用实践》读书笔记(4)
![70000 words of detailed explanation of the whole process of pad openvino [CPU] - from environment configuration to model deployment](/img/3f/36a67544deceb3d3789b500efde89c.jpg)
70000 words of detailed explanation of the whole process of pad openvino [CPU] - from environment configuration to model deployment

buuctf-pwn write-ups (8)

Webrtc quickly set up video call and video conference

509. Fibonacci number, all paths of climbing stairs, minimum cost of climbing stairs

How much computing power does transformer have

Review | categories and mechanisms of action of covid-19 neutralizing antibodies and small molecule drugs
随机推荐
STC8H开发(十二): I2C驱动AT24C08,AT24C32系列EEPROM存储
MySQL installation and configuration
Invalid revision: 3.18.1-g262b901-dirty
【微服务】Nacos集群搭建以及加载文件配置
buuctf-pwn write-ups (8)
Arcpy 利用updatelayer函数改变图层的符号系统
BeanFactoryPostProcessor 与 BeanPostProcessor 相关子类概述
Learning multi-level structural information for small organ segmentation
198. House raiding
复合非线性反馈控制(二)
AWT introduction
Layoutmanager layout manager: flowlayout, borderlayout, GridLayout, gridbaglayout, CardLayout, BoxLayout
My NVIDIA developer journey - optimizing graphics card performance
QT 获取随机颜色值设置label背景色 代码
Design and implementation of tcp/ip series overview
Design and implementation of redis 7.0 multi part AOF
Webrtc quickly set up video call and video conference
Vant --- detailed explanation and use of list component in vant
AWT common components, FileDialog file selection box
Fast power (template)