您的位置:首页 > 其它

House Robber III:打家劫舍 在二叉树结构中取非相邻元素求和取最大

2017-10-01 14:51 639 查看
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.

Example 1:

3
/ \
2   3
\   \
3   1

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

Example 2:

3
/ \
4   5
/ \   \
1   3   1

Maximum amount of money the thief can rob = 4 + 5 = 9.

思路一:递归穷举。比较本节点与孙节点之和、儿节点之和之间取最者。

public int rob(TreeNode root) {
if (root == null) return 0;
int val = 0;
if(root.left!=null){
val += rob(root.left.left);
val += rob(root.left.right);
}
if(root.right!=null){
val += rob(root.right.left);
val += rob(root.right.right);
}
return Math.max(val+root.val,(rob(root.left)+rob(root.right)));
}
思路二:改进递归,节省每一步计算中间值,因为儿节点又是孙节点的父节点,会重复计算,所以把计算的中间值存储到hash表中。

public int get(TreeNode root,HashMap<TreeNode,Integer> map) {
if (root == null) return 0;
if (map.containsKey(root)) return map.get(root);
int val = 0;
if(root.left!=null){
val += get(root.left.left,map);
val += get(root.left.right,map);
}
if(root.right!=null){
val += get(root.right.left,map);
val += get(root.right.right,map);
}
int x = Math.max(val+root.val,(get(root.left,map)+get(root.right,map)));
map.put(root,x);
return x;
}
public int rob(TreeNode root) {
return get(root,new HashMap<TreeNode,Integer>());
}

思路三:对每个节点增加存储信息的位置,降低运算时间。

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/

class Solution {
public int[] get(TreeNode n){
if(n==null) return new int[2];
int[] lstrategy = get(n.left);//0表示不取,1表示取
int[] rstrategy = get(n.right);//
int[] nstrategy = new int[2];
nstrategy[0] = Math.max(lstrategy[0],lstrategy[1])+Math.max(rstrategy[0],rstrategy[1]); ; //strategy[0]表式不取本节点的策略取值,strategy[1]表式取本节点与孙节点的策略取值
nstrategy[1] = n.val + lstrategy[0] + rstrategy[0];
return nstrategy;
}

public int rob(TreeNode root) {
if (root == null) return 0;
int[] result = get(root);
return Math.max(result[0],result[1]);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: