1、题目描述:
2、题解:
方法1:递归,DFS
超时
最优子结构:4个孙子偷的钱+爷爷的钱 VS 两个儿子偷的钱 哪个多
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rob(self, root: TreeNode) -> int:
#递归,超时
#4个孙子偷的钱+爷爷的钱 VS 两个儿子偷的钱 哪个多
if not root:return 0
money = root.val
if root.left:
money += self.rob(root.left.left) + self.rob(root.left.right)
if root.right:
money += self.rob(root.right.left) + self.rob(root.right.right)
return max(money,self.rob(root.left) + self.rob(root.right))
方法2:记忆化递归
对方法1进行改进,可以看到很多重复子问题:在求孙子偷钱时,儿子偷钱也求了,造成重复计算。所以在递归时,加一个字典memo,用来记录以及计算过的节点的取得的最多的金钱。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rob(self, root: TreeNode) -> int:
#记忆化递归
def rob_helper(root,memo):
if not root:return 0
if root in memo:return memo[root]
money = root.val
if root.left:
money += rob_helper(root.left.left,memo) + rob_helper(root.left.right,memo)
if root.right:
money += rob_helper(root.right.left,memo) + rob_helper(root.right.right,memo)
res = max(money,rob_helper(root.left,memo) + rob_helper(root.right,memo))
memo[root] = res
return res
memo = {}
return rob_helper(root,memo)
方法3:动态规划
动态规划问题,弄清楚三点:
1、重复子问题;
2、最优子结构;
3、无后效性。
动态规划:
1、状态定义;
2、状态转移方程;
3、初始化;base case
4、输出;
5、思考状态压缩。
可以用递归去求,但是会存在重叠子问题,加个备忘录可以解决重复问题。
思路:
状态定义:
由方法1和方法2,可以很容易得到下面的定义:res = [0,0] 其中res[0]表示该结点抢,res[1]表示该结点不抢
状态转移方程:
还是用递归去求,左、右子树的递归值
该结点处不抢,则res[0] = 左子树的最高金额 + 右子树的最高金额
该结点抢,则两个儿子结点不能抢,res[1] = root.val + 不抢左子树 + 不抢右子树
初始化 :
res = [0,0]
Python代码如下:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rob(self, root: TreeNode) -> int:
#动态规划
def rob_helper(root):
if not root:return [0,0]
res = [0] * 2
left = rob_helper(root.left)
right = rob_helper(root.right)
res[0] = max(left[0],left[1]) + max(right[0],right[1])
res[1] = left[0] + right[0] + root.val
return res
res = rob_helper(root)
return max(res[0],res[1])
3、复杂度分析:
方法1:
时间复杂度:O(N)
空间复杂度:O(N)
方法2:
时间复杂度:O(N)
空间复杂度:O(N)
方法3:
时间复杂度:O(N)
空间复杂度:O(N)