当前位置:网站首页>树形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;
}
边栏推荐
- QT releases multilingual International Translation
- AWT introduction
- How to get the parent node of all nodes in El tree
- C實現貪吃蛇小遊戲
- 体验碎周报第 102 期(2022.7.4)
- fastjson
- 2022.7.2-----leetcode.871
- JSON web token -- comparison between JWT and traditional session login authentication
- How to avoid JVM memory leakage?
- Invalid bound statement (not found): com. example. mapper. TblUserRecordMapper. login
猜你喜欢
Gridview出现滚动条,组件冲突,如何解决
报错cvc-complex-type.2.4.a: 发现了以元素 ‘base-extension‘ 开头的无效内容。应以 ‘{layoutlib}‘ 之一开头。
C language exercises (recursion)
[excel] PivotChart
My NVIDIA developer journey - optimizing graphics card performance
如何展开Collapse 的所有折叠面板
Detectron:训练自己的数据集——将自己的数据格式转换成COCO格式
Arcpy 利用updatelayer函数改变图层的符号系统
js arguments参数使用和详解
测试岗的中年危机该如何选择?是坚守还是另寻出路?且看下文
随机推荐
fastjson
Design and implementation of redis 7.0 multi part AOF
Nexus 6p downgraded from 8.0 to 6.0+root
How to choose the middle-aged crisis of the testing post? Stick to it or find another way out? See below
Detectron:训练自己的数据集——将自己的数据格式转换成COCO格式
Invalid revision: 3.18.1-g262b901-dirty
JS execution mechanism
C realize Snake games
Kubernets first meeting
[excel] PivotChart
ABAP:OOALV实现增删改查功能
2022.7.2-----leetcode. eight hundred and seventy-one
How to implement cross domain requests
Design and implementation of tcp/ip series overview
JSON web token -- comparison between JWT and traditional session login authentication
webrtc 快速搭建 视频通话 视频会议
如何实现视频平台会员多账号登录
Configure cross compilation tool chain and environment variables
Online shrimp music will be closed in January next year. Netizens call No
[untitled]