当前位置:网站首页>树形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
- 分布式CAP理论
- js arguments参数使用和详解
- 【无标题】
- Overview of relevant subclasses of beanfactorypostprocessor and beanpostprocessor
- Luogu deep foundation part 1 Introduction to language Chapter 5 array and data batch storage
- JSON web token -- comparison between JWT and traditional session login authentication
- Design and implementation of redis 7.0 multi part AOF
- 手动对list进行分页(参数list ,当前页,页面大小)
- A little understanding of GSLB (global server load balance) technology
猜你喜欢
How to solve the component conflicts caused by scrollbars in GridView
509. Fibonacci number, all paths of climbing stairs, minimum cost of climbing stairs
Design and implementation of redis 7.0 multi part AOF
每周小结(*63):关于正能量
Distributed cap theory
Arcpy 利用updatelayer函数改变图层的符号系统
Impact relay jc-7/11/dc110v
注释与注解
Detailed explanation of common APIs for component and container containers: frame, panel, scrollpane
buuctf-pwn write-ups (8)
随机推荐
AWT introduction
fastjson
STC8H开发(十二): I2C驱动AT24C08,AT24C32系列EEPROM存储
Arc135 a (time complexity analysis)
HMS v1.0 appointment.php editid参数 SQL注入漏洞(CVE-2022-25491)
[microservice] Nacos cluster building and loading file configuration
746. Climb stairs with minimum cost
Practical gadget instructions
Notes and notes
Input displays the currently selected picture
检漏继电器JY82-2P
Grounding relay dd-1/60
每周小结(*63):关于正能量
QT qtablewidget table column top requirements ideas and codes
Compound nonlinear feedback control (2)
AWT介绍
Kubernets first meeting
2022.7.2-----leetcode.871
C language - Blue Bridge Cup - Snake filling
注释与注解