Leetcode 337. House Robber III

来源:互联网 发布:mysql 更改character 编辑:程序博客网 时间:2024/05/21 17:38

Naive solution. There are many overlapping sub problems.

e.g. if we rob(root), we need to know rob(left), rob(right), rob(left.left), rob(left.right), ...

then, say if we want to rob(root.left), the algorithm below calculates rob(left.left), rob(left.right) again.

/** * There are two choices, rob root house or skip the root house. * Take the maximum of the two choices.  * If we choose to rob the root, then we cannot rob the left and right child of the root. * robRoot = root.val + root.left.left + root.left.right + root.right.left + root.right.right * If we choose not to rob the root,  * robNoRoot = root.left + root.right * Then take the maximum as profit, * money = max(robRoot, robNoRoot) */ public class Solution {    public int rob(TreeNode root) {        if (root == null) return 0;        int robRoot = root.val;                // rob the root house        if (root.left != null) {            robRoot += rob(root.left.left) + rob(root.left.right);        }        if (root.right != null) {            robRoot += rob(root.right.left) + rob(root.right.right);        }                return Math.max(robRoot, rob(root.left)+rob(root.right));    }}
Using a hashmap to save the result for every root so that we can avoid duplicate calculating.

public class Solution {    public int rob(TreeNode root) {        return helper(root, new HashMap<>());    }        public static int helper(TreeNode r, HashMap<TreeNode, Integer> map) {        if (r == null) return 0;        if (map.containsKey(r)) return map.get(r);                int robRoot = r.val;                // rob the root house        if (r.left != null)            robRoot += helper(r.left.left, map) + helper(r.left.right, map);        if (r.right != null)            robRoot += helper(r.right.left, map) + helper(r.right.right, map);                    int money = Math.max(robRoot, helper(r.left, map) + helper(r.right, map));        map.put(r, money);                return money;    }}




0 0
原创粉丝点击