337. 打家劫舍 III(逐句解释代码)

61 篇文章 0 订阅
package LeetCode.OneToFiveHundred;

import LeetCode.TreeNode;

import java.util.HashMap;

public class ThreeHundredsAndThirtySeven {
    public int rob(TreeNode root) {
        HashMap<TreeNode, Integer> hashMap = new HashMap<>();
        return helper(root, hashMap);
    }
    private int helper(TreeNode root, HashMap<TreeNode, Integer> hashMap){
        if (root == null) return 0;
        // 检查在 map 中是否已经算过当前的层数了
        if (hashMap.containsKey(root)) return hashMap.get(root);
        int money = root.val;
        // 计算孙子节点的值,直接统计
        if (root.left != null)
            money += (helper(root.left.left, hashMap) + helper(root.left.right, hashMap));
        if (root.right != null)
            money += (helper(root.right.left, hashMap) + helper(root.right.right, hashMap));
        // 用爷爷节点的值根儿子结点的值进行比较,此处爷爷节点包括孙子节点以及后序的所有可能节点,儿子节点相同
        int ans = Math.max(money, helper(root.left, hashMap) + helper(root.right, hashMap));
        // 将结果存储,记忆化,减少时间消耗
        hashMap.put(root,ans);
        return ans;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值