您的位置:首页 > 其它

**[Lintcode] House Rober III 打劫房屋 III

2016-10-07 17:04 309 查看
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart
thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night.
Determine the maximum amount of money the thief can rob tonight without alerting the police.

Have you met this question in a real interview? 

Yes

Example

3
/ \
2   3
\   \
3   1

Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.

分析:与上两道题不同,这道题无法使用DP解决。但是涉及到树的问题一般可以通过递归解决。将Root,Root.left和Root.right看作一组,针对每一组,有两种情况,

Root,Root.left的孩子和Root.right孩子,或者root.left和root.right. 这里我们分别计算这两种情况并且取最大值即可

/**
* 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
*/

Map<TreeNode, Integer> res = new HashMap<TreeNode, Integer>();

public int houseRobber3(TreeNode root) {
if(root == null) return 0;
if(res.get(root) != null) return res.get(root);

int includeRoot = root.val;
if(root.left != null) {
includeRoot += houseRobber3(root.left.left);
includeRoot += houseRobber3(root.left.right);
}
if(root.right != null) {
includeRoot += houseRobber3(root.right.left);
includeRoot += houseRobber3(root.right.right);
}

int exceptRoot = houseRobber3(root.left) + houseRobber3(root.right);

int val = Math.max(includeRoot, exceptRoot);
res.put(root, val);
return val;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  lintcode