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; }
当你看清人们的真相,于是你知道了,你可以忍受孤独