337. House Robber III

本文探讨了一个智能窃贼如何在遵循特定规则的情况下,从形成二叉树结构的房屋中最大化抢劫金额的问题。通过递归算法,文章提供了三种不同语言的实现方案,包括C++、Java和Python,展示了如何避免同时抢劫直接相连的房屋以防止报警。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night.

Determine the maximum amount of money the thief can rob tonight without alerting the police.

Example 1:

Input: [3,2,3,null,3,null,1]

     3
    / \
   2   3
    \   \ 
     3   1

Output: 7 
Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.

Example 2:

Input: [3,4,5,1,3,null,1]

     3
    / \
   4   5
  / \   \ 
 1   3   1

Output: 9
Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.
 

Approach #1: C++. [native]

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int rob(TreeNode* root) {
        if (root == NULL) return 0;
        
        int val = 0;
        
        if (root->left != NULL) 
            val += rob(root->left->left) + rob(root->left->right);

        if (root->right != NULL) 
            val += rob(root->right->left) + rob(root->right->right);

        return max(val+root->val, rob(root->left)+rob(root->right));
    }
};

  

Approach #2: Java. [native + memory]

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int rob(TreeNode root) {
        if (root == null) return 0;
        
        return helper(root, new HashMap<>());
    }
    
    private int helper(TreeNode root, Map<TreeNode, Integer> map) {
        if (root == null) return 0;
        if (map.containsKey(root)) return map.get(root);
        int val = 0;
        if (root.left != null) 
            val += helper(root.left.left, map) + helper(root.left.right, map);
        if (root.right != null)
            val += helper(root.right.left, map) + helper(root.right.right, map);
        val = Math.max(val + root.val, helper(root.left, map) + helper(root.right, map));
        map.put(root, val);
        
        return val;
    }
}

  

Approach #3: Python. [dfs + DP]

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def rob(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        def superRob(root):
            if root == None:
                return (0, 0)
            
            left, right = superRob(root.left), superRob(root.right)
            
            now = left[1] + right[1] + root.val
            
            later = max(left) + max(right)
            
            return (now, later)
        
        return max(superRob(root))

  

Analysis:

Maybe this is very hard to understand. I aways fall into the endless recursive. In those similar question we shouldn't try to image the process using our brain. 

what we can do is to think the problem if or not can resolve the big problem into a little scope with the same condition . if so we should find the end condition 

to stop the recursive and return the value(ie. 0 or someting other).

转载于:https://www.cnblogs.com/ruruozhenhao/p/10105045.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值