337. 打家劫舍 III
题目描述
小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为 root 。
除了 root 之外,每栋房子有且只有一个“父“房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 如果 两个直接相连的房子在同一天晚上被打劫 ,房屋将自动报警。
给定二叉树的 root 。返回 在不触动警报的情况下 ,小偷能够盗取的最高金额 。
解题思路
思路一: 暴力法
两种偷法:
- 偷root、 root.left.left、 root.left.right、root.left.left.left.left…
- 偷root.left、root.right、root.left.left.left、 root.left.left.right…
实现代码如下:
/**
* @param {TreeNode} root
* @return {number}
*/
var rob = function(root) {
if (root == null) {
return 0;
}
let money = root.val;
if (root.left !== null) {
money += rob(root.left.left) + rob(root.left.right)
}
if (root.right !== null) {
money += rob(root.right.left) + rob(root.right.right)
}
return Math.max(money, rob(root.left) + rob(root.right));
};
但是这种解法会提示超出时间限制
思路二: 优化, 利用缓存
可以利用缓存对重复子问题进行优化。 利用Map来存储结构
优化代码如下:
/**
* @param {TreeNode} root
* @return {number}
*/
var rob = function(root) {
let memo = new Map();
return robInternal(root, memo);
}
const robInternal = function(root, memo) {
if (root == null) return 0;
if (memo.has(root)) return memo.get(root);
let money = root.val;
if (root.left != null) {
money += (robInternal(root.left.left, memo) + robInternal(root.left.right, memo));
}
if (root.right != null) {
money += (robInternal(root.right.left, memo) + robInternal(root.right.right, memo));
}
let result = Math.max(money, robInternal(root.left, memo) + robInternal(root.right, memo));
memo.set(root, result);
return result;
}
思路三: 动态规划
每个节点都可以选择偷或者不偷:
- 当前节点偷, 则两个子节点不能选择偷;
- 当前节点不偷, 两个子节点只需要拿最多的钱出来就行(两个孩子节点偷不偷没关系)
我们使用一个大小为 2 的数组来表示 let res = [0, 0]
0 代表不偷,1 代表偷
任何一个节点能偷到的最大钱的状态可以定义为
- 当前节点选择不偷:当前节点能偷到的最大钱数 = 左节点能偷到的钱 + 右节点能偷到的钱
- 当前节点选择偷:当前节点能偷到的最大钱数 = 左节点选择自己不偷时能得到的钱 + 右节点选择不偷时能得到的钱 + 当前节点的钱数
表示为公式如下:
res[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
res[1] = left[0] + right[0] + root.val
实现代码如下:
/**
* @param {TreeNode} root
* @return {number}
*/
var rob = function(root) {
let result = robInternal(root);
return Math.max(result[0], result[1]);
}
const robInternal = function(root) {
if (root == null) return [0, 0];
let result = [0, 0];
let left = robInternal(root.left),
right = robInternal(root.right);
result[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
result[1] = left[0] + right[0] + root.val;
return result;
}
- 时间复杂度:O(n)
- 空间复杂度:O(n), 递归会使用到栈空间
参考资料
三种方法解决树形动态规划问题-从入门级代码到高效树形动态规划代码实现 - 打家劫舍 III - 力扣(LeetCode)