Leetcode 337 打家劫舍III 树形DP
JAVA:
public final int rob(TreeNode root) {
Map<String, Integer> cache = new HashMap<String, Integer>();
return Math.max(rob(root, true, cache), rob(root, false, cache));
}
public final int rob(TreeNode root, boolean stro, Map<String, Integer> cache) { if (root == null) { return 0; } String key = root.hashCode() + String.valueOf(stro); if (cache.containsKey(key)) { return cache.get(key); } int leftTrue = 0; int rightTrue = 0; int leftFalse = 0; int rightFalse = 0; if (root.left != null) { leftTrue = rob(root.left, true, cache); leftFalse = rob(root.left, false, cache); } if (root.right != null) { rightTrue = rob(root.right, true, cache); rightFalse = rob(root.right, false, cache); } int an = 0; if (stro) { an = rightFalse + leftFalse + root.val; } else { an = Math.max(rightTrue + leftTrue, rightFalse + leftTrue); an = Math.max(an, rightTrue + leftFalse); an = Math.max(an, rightFalse + leftFalse); } cache.put(key, an); return an; }
优化下写法:
Map<TreeNode, Integer> t = new HashMap<TreeNode, Integer>(); Map<TreeNode, Integer> f = new HashMap<TreeNode, Integer>(); public final int rob(TreeNode root) { search(root); return Math.max(t.getOrDefault(root, 0), f.getOrDefault(root, 0)); } private final void search(TreeNode root) { if (root == null) { return; } search(root.left); search(root.right); t.put(root, f.getOrDefault(root.left, 0) + f.getOrDefault(root.right, 0) + root.val); f.put(root, Math.max(t.getOrDefault(root.left, 0), f.getOrDefault(root.left, 0)) + Math.max(t.getOrDefault(root.right, 0), f.getOrDefault(root.right, 0))); }
JS:
var rob = function (root) { Map.prototype.getOrDefault = function (key) { if (this.has(key)) { return this.get(key); } return 0; } let f = new Map(); let t = new Map(); search(root, f, t); return max(f.getOrDefault(root), t.getOrDefault(root)); }; var search = function (root, f, t) { if (root == undefined) { return; } search(root.left,f,t); search(root.right,f,t); t.set(root, root.val + f.getOrDefault(root.left) + f.getOrDefault(root.right)); f.set(root, max(f.getOrDefault(root.left), t.getOrDefault(root.left)) + max(f.getOrDefault(root.right), t.getOrDefault(root.right))); } var max = function (n0, n1) { return n0 > n1 ? n0 : n1; }
当你看清人们的真相,于是你知道了,你可以忍受孤独
分类:
数据结构与算法
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构