Appearance
0337-打家劫舍III
https://leetcode.cn/problems/house-robber-iii
在上次打劫完一条街道之后和一圈房屋后,小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为“根”。 除了“根”之外,每栋房子有且只有一个“父“房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 如果两个直接相连的房子在同一天晚上被打劫,房屋将自动报警。
计算在不触动警报的情况下,小偷一晚能够盗取的最高金额。
示例 1:
输入: [3,2,3,null,3,null,1]
3
/ \
2 3
\ \
3 1
输出: 7
解释: 小偷一晚能够盗取的最高金额 = 3 + 3 + 1 = 7.
示例 2:
输入: [3,4,5,1,3,null,1]
3
/ \
4 5
/ \ \
1 3 1
输出: 9
解释: 小偷一晚能够盗取的最高金额 = 4 + 5 = 9.
思路
基于树的动态规划 每个节点都有选择或者不选择,两种状态,我们将这两个状态返回。
重点:返回选择或者不选择
参考代码
csharp
public class Solution {
public int Rob(TreeNode root) {
int[] result = rob(root);
return Math.Max(result[0],result[1]);
}
//a[0]表示不选择, a[1]表示选择
private int[] rob(TreeNode root){
if(root == null){
return new int[]{0,0};
}
int[] left = rob(root.left);
int[] right = rob(root.right);
int notChooseSelf = Math.Max(left[0],left[1]) + Math.Max(right[0],right[1]);
int chooseSelf = root.val + left[0] + right[0];
return new int[]{notChooseSelf,chooseSelf};
}
}
参考代码:复习:2022-04-02
csharp
public class Solution {
public int Rob(TreeNode root) {
int[] result = RobNode(root);
return Math.Max(result[0],result[1]);
}
// int[] 数组 0 表示不选择, 1表示选择
private int[] RobNode(TreeNode root){
if(root == null){
return new int[]{0,0};
}
int[] left = RobNode(root.left);
int[] right = RobNode(root.right);
//不选择自己
int notChooseSelf = Math.Max(left[0],left[1]) + Math.Max(right[0],right[1]);
int chooseSelf = root.val + left[0] + right[0];
return new int[]{notChooseSelf,chooseSelf};
}
}
复习:2022-05-03
注意 不选择自己的时候,子节点是可以选择也可以不选择,选取最大值
csharp
public class Solution {
public int Rob(TreeNode root) {
int[] result = RobNode(root);
return Math.Max(result[0],result[1]);
}
public int[] RobNode(TreeNode root){
//返回选择自己或者不选择自己
if(root == null){
return new int[]{0,0};
}
int[] left = RobNode(root.left);
int[] right = RobNode(root.right);
int notChoose = Math.Max(left[0],left[1]) + Math.Max(right[0],right[1]);
int choose = root.val + left[0] + right[0];
return new int[]{notChoose,choose};
}
}
AlgoPress