翻转字符串
题目
在上次打劫完一条街道之后和一圈房屋之后,窃贼又发现了一个新的可以打劫的地方,但这次所有的房子组成的区域比较奇怪,聪明的窃贼考察地形之后,发现这次的地形是一颗二叉树。与前两次偷窃相似的是每个房子都存放着特定金额的钱。你面临的唯一约束条件是:相邻的房子装着相互联系的防盗系统,且当相邻的两个房子同一天被打劫时,该系统会自动报警。
算一算,如果今晚去打劫,你最多可以得到多少钱,当然在不触动报警装置的情况下。注意事项
这题是House Robber和House Robber II的扩展,只不过这次地形由直线和圈变成了二叉树样例
窃贼最多能偷窃的金钱数是 3 + 3 + 1 = 7.
窃贼最多能偷窃的金钱数是 4 + 5 = 9.题解
以dp[i][0]表示以i为根的子树不偷根节点能获得的最高价值,以dp[i][1]表示以i为根的子树偷根节点能获得的最高价值(处理方式和392.House Robber-打劫房屋(中等题)类似),最后取最大值即可。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: The maximum amount of money you can rob tonight
*/
public int houseRobber3(TreeNode root) {
int[] res = dp(root);
return Math.max(res[0],res[1]);
}
private int[] dp(TreeNode root)
{
if (root == null)
{
return new int[]{0,0};
}
int[] left = dp(root.left);
int[] right = dp(root.right);
int[] now = new int[2];
now[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
now[1] = left[0] + right[0] + root.val;
return now;
}
}
Last Update 2016.12.4