java 树形dp
很多时候需要求最大值最小值啥的可以用PriorityQueue,PriorityQueue small=new PriorityQueue<>(Collections.reverseOrder());这个里面没看到decreaseKey或者increaseKey操作,需要可以用remove,然后改变值再insert来实现。
树形dp:本来想着可以构造一个树节点到 dp数据存储的映射,然后用后序遍历计算每个节点的dp值并存在hashmap里,但是这个dp数据可以直接存在虚拟机栈的局部变量并且作为返回值在后序遍历时往上传,传完了之后就找不到对应的数据了,但是可以返回前用map保存。和dfs记忆化很类似,这里不需要记忆。
这是leetcode337题答案,如果换成树(美团笔试),并且用图结构保存,可以先随便找个点做根,然后help方法的形参加上父节点,以方便在图中判断哪些是子节点。如果换成图,目前只想到暴力dfs,将所有节点放入链表,然后像得到所有组合数那样,尝试所有组合,如果有相邻的图节点就去掉那些组合。
class Solution {
public static int rob(TreeNode root) {
int[] help = help(root);
return Math.max(help[0], help[1]);//0不偷 1偷
}
static int[] help(TreeNode root) {
if (root == null) {
return new int[2];
}
int res[] = new int[2];
int[] help = help(root.left);
int[] help1 = help(root.right);
res[0] = Math.max(help[0], help[1]) + Math.max(help1[0], help1[1]);
res[1] = help[0] + help1[0] + root.val;
return res;
}
}