心路历程:
还是经典的动态规划题,建模思路:
状态:第i个房间;j偷或者不偷
候选动作:偷 或者不偷
返回值:当前状态获得的最大金额
注意的点:
1、当计算当前结点被偷时,注意node.val不要加重复了
2、objective对象也是hashable的,可以@cache处理
解法:动态规划
python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def rob(self, root: Optional[TreeNode]) -> int:
@cache
def dp(node, j):
# if not node: return 0
if j == 0:
res1, res2 = 0, 0
if node.left: res1 = max(dp(node.left, 1), dp(node.left, 0))
if node.right: res2 = max(dp(node.right, 1), dp(node.right, 0))
return res1 + res2
else: # 这块的node.val不要加重复了!!!
res1, res2 = 0, 0
if node.left: res1 = dp(node.left, 0)
if node.right: res2 = dp(node.right, 0)
return res1 + res2 + node.val
return max(dp(root, 1), dp(root, 0))