您的位置:首页 > 其它

LeetCode House Robber III

2016-03-18 23:53 190 查看
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.

小偷偷东西的问题,房子是二叉树的结构,相连的房子不能一起偷,不然警报会响。求能偷到的最大值

先看代码。

/**

* Definition for a binary tree node.

* public class TreeNode {

* int val;

* TreeNode left;

* TreeNode right;

* TreeNode(int x) { val = x; }

* }

*/

public class Solution {

public int rob(TreeNode root) {

Result result=getResult(root);

return Math.max(result.include,result.exclude);

}

//!!!!!!!!!!!!!!!!!!!!!!!!

public Result getResult(TreeNode root){

if(root==null) return new Result(0,0);

Result l=getResult(root.left);

Result r=getResult(root.right);

int exclude=Math.max(l.include, l.exclude)+ Math.max(r.include, r.exclude);

int exclude=l.include+r.include;

return new Result(include,exclude);

}


class Result{

int include;

int exclude;

Result(int include,int exclude){

this.include=include;

this.exclude=exclude;

}

}

}

感觉自己算法的水平还不是很够,上网查了下,这种类型的题目好像考到了动态规划。

其实思路是有的,但不够清晰,不知道具体如何实现。

程序中进行了假设分组,分为偷的房子的总价值和没偷的房子的总价值。最后比较两者取最大值,就是小偷能偷到的最大财产。

定义了一个Result类,用来存储偷的价值和没偷的价值。

在getReult方法中,进行不断迭代(不知道这里这么说准不准确)获取最终的Result。

代码中int exclude=Math.max(l.include, l.exclude)+ Math.max(r.include, r.exclude);获取没偷房子的最大总价值。

为什么这里是这么写呢?因为该root已经是归于not get里面了,因此要获取没偷房子的最大总价值就是比较l.include, l.exclude以及

r.include,
r.exclude,取int exclude=Math.max(l.include, l.exclude)+ Math.max(r.include, r.exclude)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: