难度: Medium
原题连接
内容描述
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.
思路 1 - 时间复杂度: O(N)- 空间复杂度: O(1)******
这个post完整且生动地描述了从开始的粗糙递归到用记忆化搜索再到最后的原始递归中记录状态的优化过程,真是好文
从root开始抢起来,最大能抢到的两个可能: 抢root和不抢root
递归,对于每个node,我们return的是从这个node能抢到的最大值,以及不抢它能获得的最大值
beats 99.64%
class Solution:
def rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def dfs(root):
if not root:
return 0, 0
pickl, nopickl = dfs(root.left)
pickr, nopickr = dfs(root.right)
pick = nopickl + nopickr + root.val
nopick = max(pickl, nopickl) + max(pickr, nopickr)
return (pick, nopick)
return max(dfs(root))