打家劫舍 III (House Robber III)

 

思路:dp代表了当前节点选和不选的二元组

// @Title: 打家劫舍 III (House Robber III)
// @Author: qisiii
// @Date: 2024-11-18 22:41:47
// @Runtime: 0 ms
// @Memory: 43.2 MB
// @comment: dp代表了当前节点选和不选的二元组
// @flag: GREEN
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int rob(TreeNode root) {
        int[] res=robDP(root);
        return Math.max(res[0],res[1]);
    }

    private int[] robDP(TreeNode root){
        int[] dp=new int[2];
        if(root==null){
            return dp;
        }
        int[] left=robDP(root.left);
        int[] right=robDP(root.right);
        dp[0]=Math.max(left[0],left[1])+Math.max(right[0],right[1]);
        dp[1]=root.val+left[0]+right[0];
        return dp;
    }
}

+++ title = “打家劫舍 III (House Robber III)” draft = false +++

思路:暴力+hash

// @Title: 打家劫舍 III (House Robber III)
// @Author: qisiii
// @Date: 2024-11-18 22:28:10
// @Runtime: 2 ms
// @Memory: 43.3 MB
// @comment: 暴力+hash
// @flag: WHITE
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    Map<TreeNode,Integer> map=new HashMap<>();
    public int rob(TreeNode root) {
        if(root==null){
            return 0;
        }
        if(map.containsKey(root)){
            return map.get(root);
        }
        int val=root.val;
        if(root.left==null&&root.right==null){
            return val;
        }
        if(root.left!=null){
            val=val+rob(root.left.left)+rob(root.left.right);
        }
        if(root.right!=null){
            val=val+rob(root.right.left)+rob(root.right.right);
        }
        Integer result=Math.max(val,rob(root.left)+rob(root.right));
        map.put(root,result);
        return result;
        
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-12-27