博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode[337] House Robber III
阅读量:7091 次
发布时间:2019-06-28

本文共 1429 字,大约阅读时间需要 4 分钟。

LeetCode[337] House Robber III

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:

3/ \2   3\   \  3   1

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

Example 2:

3/ \4   5/ \   \ 1   3   1

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

recursion + Memorization

复杂度

O(N), O(lgN)

思路

对于每一个位置来说,考虑两种情况, Max(child, subchild + root.val).
分别对child和subchild再进行recursion计算。

用map对已经计算过的node进行保留,避免重复计算。

代码

public int rob(TreeNode root) {    // Base case;    if(root == null) return 0;    if(root.left == null && root.right == null) return root.val;    if(map.containsKey(root)) return map.get(root);    int child = 0, subchild = 0;    if(root.left != null) {        child += rob(root.left);        subchild += rob(root.left.left) + rob(root.left.right);    }    if(root.right != null) {        child += rob(root.right);        subchild += rob(root.right.left) + rob(root.right.right);    }    int val = Math.max(child, subchild + root.val);    map.put(root, val);    return val;}

转载地址:http://doiql.baihongyu.com/

你可能感兴趣的文章
Atitit.iso格式蓝光 BDMV 结构说明
查看>>
MySQL的create table as 与 like区别(转)
查看>>
Linux学习历程(持续更新整理中)
查看>>
Linux查看物理CPU个数、核数、逻辑CPU个数
查看>>
软件设计模式详解:OCP原则
查看>>
Apache服务器常规操作
查看>>
qt cef嵌入web
查看>>
Java程序员面试失败的5大原因
查看>>
过滤器(Filter)
查看>>
外观模式
查看>>
Webmin|Linux管理员远程管理工具
查看>>
【温故而知新-Javascript】比较 undefined 和 null 值
查看>>
CentOS中iptables防火墙 开放80端口方法
查看>>
Kafka 在行动:7步实现从RDBMS到Hadoop的实时流传输
查看>>
[内核]Linux workqueue
查看>>
云计算开始。。。
查看>>
利用sys.dm_db_index_physical_stats查看索引碎片等数据
查看>>
jquery html动态添加的元素绑定事件详解
查看>>
日常英语---九、MapleStory Link Skills Guide
查看>>
最强科技实力支撑海尔走出“全球化”道路
查看>>