当前位置:网站首页>树形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;
}
边栏推荐
- C语言中的函数(详解)
- 509. Fibonacci number, all paths of climbing stairs, minimum cost of climbing stairs
- Learning multi-level structural information for small organ segmentation
- Leakage detection relay jy82-2p
- How to help others effectively
- buuctf-pwn write-ups (8)
- (4) Canal multi instance use
- HMS v1.0 appointment.php editid参数 SQL注入漏洞(CVE-2022-25491)
- 《ClickHouse原理解析与应用实践》读书笔记(4)
- js获取对象中嵌套的属性值
猜你喜欢
Arc135 C (the proof is not very clear)
C实现贪吃蛇小游戏
Json Web token - jwt vs. Traditional session login Authentication
QT get random color value and set label background color code
Error CVC complex type 2.4. a: Invalid content beginning with element 'base extension' was found. Should start with one of '{layoutlib}'.
AWT common components, FileDialog file selection box
ES6 modularization
AWT介绍
C réaliser des jeux de serpents gourmands
HMS v1.0 appointment. PHP editid parameter SQL injection vulnerability (cve-2022-25491)
随机推荐
Online shrimp music will be closed in January next year. Netizens call No
一键过滤选择百度网盘文件
JS get the attribute values nested in the object
198. House raiding
ES6 模块化
How to get the parent node of all nodes in El tree
How much computing power does transformer have
Design and implementation of redis 7.0 multi part AOF
Leetcode question brushing record | 206_ Reverse linked list
lightroom 导入图片灰色/黑色矩形 多显示器
LayoutManager布局管理器:FlowLayout、BorderLayout、GridLayout、GridBagLayout、CardLayout、BoxLayout
如何展开Collapse 的所有折叠面板
buuctf-pwn write-ups (8)
Manually page the list (parameter list, current page, page size)
509. Fibonacci number, all paths of climbing stairs, minimum cost of climbing stairs
Considerations for testing a website
冲击继电器JC-7/11/DC110V
FRP intranet penetration, reverse proxy
JS扁平化数形结构的数组
el-select如何实现懒加载(带搜索功能)