「力扣」第 337 题:打家劫舍 III
这道题是「树形 dp」问题,如果「树形 dp」暂时不能理解的话,我感觉暂时也没有关系,先理解有「重叠子问题」,把「记忆化递归」加上。
在上次打劫完一条街道之后和一圈房屋后,小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为“根”。 除了“根”之外,每栋房子有且只有一个“父“房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 如果两个直接相连的房子在同一天晚上被打劫,房屋将自动报警。
计算在不触动警报的情况下,小偷一晚能够盗取的最高金额。
示例 1:
输入: [3,2,3,null,3,null,1] 3 / \ 2 3 \ \ 3 1 输出: 7 解释: 小偷一晚能够盗取的最高金额 = 3 + 3 + 1 = 7.
示例 2:
输入: [3,4,5,1,3,null,1] 3 / \ 4 5 / \ \ 1 3 1 输出: 9 解释: 小偷一晚能够盗取的最高金额 = 4 + 5 = 9.
分析:和 House Robber 一样,不过这次是在一个小区中,整个小区成二叉树的结构。在不触碰警报的情况下,问能够窃取的财产的最大值是多少?我觉得这个问题主要考察了分类讨论。
方法一:递归(没有记忆化,时间慢)
Java 代码:
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public class Solution {
public int rob(TreeNode root) {
if (root == null) {
return 0;
}
int val = root.val;
if (root.left != null) {
val += rob(root.left.left) + rob(root.left.right);
}
if (root.right != null) {
val += rob(root.right.left) + rob(root.right.right);
}
return Math.max(val, rob(root.left) + rob(root.right));
}
}
方法二:记忆化递归
Java 代码:
import java.util.HashMap;
import java.util.Map;
public class Solution2 {
private Map<TreeNode, Integer> memo;
private int tryRob(TreeNode node) {
if (node == null) {
return 0;
}
if (memo.containsKey(node)) {
return memo.get(node);
}
int res = node.val;
if (node.left != null) {
res += tryRob(node.left.left) + tryRob(node.left.right);
}
if (node.right != null) {
res += tryRob(node.right.left) + tryRob(node.right.right);
}
res = Math.max(res, tryRob(node.left) + tryRob(node.right));
memo.put(node, res);
return res;
}
public int rob(TreeNode root) {
memo = new HashMap<>();
return tryRob(root);
}
}
方法三:树形 dp
Java 代码:
public class Solution {
// 树形 dp + 二叉树的后序遍历
// 0 表示不打劫
// 1 表示打劫
public int rob(TreeNode root) {
int[] res = tryRob(root);
return Math.max(res[0], res[1]);
}
private int[] tryRob(TreeNode root) {
if (root == null) {
return new int[2];
}
int[] left = tryRob(root.left);
int[] right = tryRob(root.right);
int[] res = new int[2];
// 根结点不打劫 = max(左子树不打劫, 左子树打劫) + max(右子树不打劫, 右子树打劫)
res[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
// 根结点打劫 = 左右孩子结点都不能打劫
res[1] = left[0] + right[0] + root.val;
return res;
}
}