package LeetCode.OneToFiveHundred;
import LeetCode.TreeNode;
import java.util.HashMap;
public class ThreeHundredsAndThirtySeven {
public int rob(TreeNode root) {
HashMap<TreeNode, Integer> hashMap = new HashMap<>();
return helper(root, hashMap);
}
private int helper(TreeNode root, HashMap<TreeNode, Integer> hashMap){
if (root == null) return 0;
// 检查在 map 中是否已经算过当前的层数了
if (hashMap.containsKey(root)) return hashMap.get(root);
int money = root.val;
// 计算孙子节点的值,直接统计
if (root.left != null)
money += (helper(root.left.left, hashMap) + helper(root.left.right, hashMap));
if (root.right != null)
money += (helper(root.right.left, hashMap) + helper(root.right.right, hashMap));
// 用爷爷节点的值根儿子结点的值进行比较,此处爷爷节点包括孙子节点以及后序的所有可能节点,儿子节点相同
int ans = Math.max(money, helper(root.left, hashMap) + helper(root.right, hashMap));
// 将结果存储,记忆化,减少时间消耗
hashMap.put(root,ans);
return ans;
}
}
337. 打家劫舍 III(逐句解释代码)
最新推荐文章于 2025-07-20 14:30:00 发布
本文介绍了解决LeetCode上337号问题“房屋劫匪III”的算法实现,该问题涉及在一棵表示房屋的树形结构中,找到抢劫这些房屋的最大收益。使用递归加记忆化的解决方案,避免重复计算,提高算法效率。

&spm=1001.2101.3001.5002&articleId=107826103&d=1&t=3&u=f758a074cefb49e09a33552cae5bba1c)
1735

被折叠的 条评论
为什么被折叠?



