@(labuladong的算法小抄)[dp]
leetcode 337. 打家劫舍 III
题目描述
解题思路
参考:labuladong的算法小抄P205
注意,二叉树都是用自顶向下的递归形式,参考 leetcode 198.打家劫舍
中的做法
class Solution {
Map<TreeNode, Integer> memo;
public int rob(TreeNode root) {
memo = new HashMap<>();
return dp(root);
}
/* 定义:dp(root)表示从root开始做选择,一直偷到最后,能够获得的最多金额数 */
private int dp(TreeNode root) {
/* base case */
if (root == null) return 0;
if (memo.containsKey(root)) return memo.get(root);
/* 选择不偷,然后去下家做选择 */
int notSteal = dp(root.left) + dp(root.right);
/* 选择偷,然后去下下家做选择 */
int steal = root.val
+ (root.left == null ? 0 : dp(root.left.left) + dp(root.left.right))
+ (root.right == null ? 0 : dp(root.right.left) + dp(root.right.right));
int res = Math.max(steal, notSteal);
memo.put(root, res);
return res;
}
}