337. House Robber III 【M】【vip】
2016-05-11 20:43
197 查看
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:
Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
Maximum amount of money the thief can rob = 4 + 5 = 9.
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
Subscribe to
see which companies asked this question
本质上是一个树的遍历 问题
这个刚开始想错了,为什么不能用广搜呢,因为并不是如果我不rob树根,就一定要rob他的两个子节点。也就是说,有可能我只rob他的一个子节点会更好。
root ( we can rob
root but without robbing
Then we have
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.
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
Subscribe to
see which companies asked this question
本质上是一个树的遍历 问题
这个刚开始想错了,为什么不能用广搜呢,因为并不是如果我不rob树根,就一定要rob他的两个子节点。也就是说,有可能我只rob他的一个子节点会更好。
f1(node)be the value of maximum money we can rob from the subtree with
nodeas
root ( we can rob
nodeif necessary).
f2(node)be the value of maximum money we can rob from the subtree with
nodeas
root but without robbing
node.
Then we have
f2(node) = f1(node.left) + f1(node.right)and
f1(node) = max( f2(node.left)+f2(node.right)+node.value, f2(node) ).
class Solution(object): def do(self,root): if root == None: return (0,0) l = self.do(root.left) r = self.do(root.right) return (l[1] + r[1] , max(l[1] + r[1] , l[0] + r[0] + root.val)) def rob(self, root): return self.do(root)[1]
相关文章推荐
- 第二届TSCTF比赛writeup及心得-Web
- JavaScript(select onchange)的网页跳转的简单实现
- 深入理解Java:注解(Annotation)基本概念
- LeetCode:Remove Duplicates from Sorted Array
- 百思不得其姐关注模块的推荐关注中 右侧TableView刷新细节
- android pd px sp 转换
- as问题集锦
- poj1837Balance【二维01背包方法数——天平平衡】
- Windows网络编程学习笔记(2) IPV4地址协议编程
- 链表功能函数总结
- vim编程 插入 保存不退出 保存退出 退出不保存 另存为其他文件名 保存覆盖现有文件
- 简单回顾TCPIP
- [置顶] 匿名内部类
- coderforces 22C 构图水题
- 多线程网络总结
- 初识px,em,rem
- SparkR初体验
- 1002 ProblemL
- JAVA学习笔记(二)-运算符、选择语句、循环语句
- 基本位运算