Leetcode 337. House Robber III
来源:互联网 发布:知乎 扒皮 编辑:程序博客网 时间:2024/06/07 20:36
Redefine rob(root)
as a new function which will return an array of two elements, the first element of which denotes the maximum amount of money that can be robbed if root
is not robbed, while the second element signifies the maximum amount of money robbed if it is robbed.
Let's relate rob(root)
to rob(root.left)
and rob(root.right)...
, etc. For the 1st element of rob(root)
, we only need to sum up the larger elements of rob(root.left)
and rob(root.right)
, respectively, since root
is not robbed and we are free to rob its left and right subtrees. For the 2nd element of rob(root)
, however, we only need to add up the 1st elements of rob(root.left)
and rob(root.right)
, respectively, plus the value robbed from root
itself, since in this case it's guaranteed that we cannot rob the nodes of root.left
and root.right
.
定义rob(root) 返回一个有两个元素的数组。
第一个数表示: 如果root没有被抢, 最大的金钱
第一个数表示: 如果root被抢,最大的金钱
怎样把rob(root) 联系上 rob(root.left) 或是 rob(root.right)?
rob(root)的第一个数等于 rob(root.left) 和 rob(root.right) 较大的, 因为root 没有被抢,我们随意可以抢左右子树。
rob(root)的第二个数等于 rob(root.left) 和 rob(root.right) 的第一个数的和加上 root.val
public int rob(TreeNode root) { int[] res = robSub(root); return Math.max(res[0], res[1]);}private int[] robSub(TreeNode root) { if (root == null) return new int[2]; int[] left = robSub(root.left); int[] right = robSub(root.right); int[] res = new int[2]; res[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]); res[1] = root.val + left[0] + right[0]; return res;}
- [leetcode] 337. House Robber III
- LeetCode#337. House Robber III
- LeetCode *** 337. House Robber III
- [leetcode]337. House Robber III
- LeetCode-337. House Robber III
- [leetcode]337. House Robber III
- LeetCode-337.House Robber III
- LeetCode 337. House Robber III
- Leetcode 337. House Robber III
- leetcode 337. House Robber III
- LeetCode - 337. House Robber III
- 【LeetCode】337. House Robber III
- 【leetcode】337. House Robber III
- [leetcode] 337. House Robber III
- LeetCode 337. House Robber III
- 【LeetCode】337. House Robber III
- LeetCode 337. House Robber III
- LeetCode 337. House Robber III
- Leetcode House Robber 系列总结
- android如何让一个imagebutton在一个线性布局中水平居中
- 模板偏特化 and traits机制
- Java 类——权限修饰符
- Git教程 —— 分支管理
- Leetcode 337. House Robber III
- [未完]linux配置文件整理
- 布局管理器——表格布局
- 数字三角形
- 配置mybatis解决log4j未正常打印sql的问题
- Retrofit:打造自己的Converter之byte[]
- POJ 1848 Tree 笔记
- 在win7,pycharm编译器下配置第一个django程序
- 【实训】Android中xml动画定义