1. 题目
2. 思路
(1) 动态规划
- 对于每个结点,需要维护其在三种状态下以该结点为根的树的摄像头数目:
- 状态a:root一定放置摄像头,且整棵树都被监控;
- 状态b:root不一定放置摄像头,且整棵树都被监控;
- 状态c:root不一定被监控,但左右子树被监控。
- 显然,a>=b>=c,设其左右子树的状态变量为(la,lb,lc)和(ra,rb,rc),则:
- a=lc+rc+1;
- b=min(a,min(la+rb,lb+ra));
- c=min(a,lb+rb)。
- 最终结果显然是根结点在状态b下的摄像头数目。
3. 代码
public class Test {
public static void main(String[] args) {
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
public int minCameraCover(TreeNode root) {
return dfs(root)[1];
}
private int[] dfs(TreeNode root) {
if (root == null) {
return new int[]{Integer.MAX_VALUE / 2, 0, 0};
}
int[] left = dfs(root.left);
int[] right = dfs(root.right);
int[] res = new int[3];
res[0] = left[2] + right[2] + 1;
res[1] = Math.min(res[0], Math.min(left[0] + right[1], left[1] + right[0]));
res[2] = Math.min(res[0], left[1] + right[1]);
return res;
}
}