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.

Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.

这道题是之前那两道 House Robber II 和 House Robber 的拓展,这个小偷又偷出新花样了,沿着二叉树开始偷,碉堡了,题目中给的例子看似好像是要每隔一个偷一次,但实际上不一定只隔一个,比如如下这个例子:

       /

     /

   /
  

如果隔一个偷,那么是 4+2=6,其实最优解应为 4+3=7,隔了两个,所以说纯粹是怎么多怎么来,那么这种问题是很典型的递归问题,可以利用回溯法来做,因为当前的计算需要依赖之前的结果,那么对于某一个节点,如果其左子节点存在,通过递归调用函数,算出不包含左子节点返回的值,同理,如果右子节点存在,算出不包含右子节点返回的值,那么此节点的最大值可能有两种情况,一种是该节点值加上不包含左子节点和右子节点的返回值之和,另一种是左右子节点返回值之和不包含当期节点值,取两者的较大值返回即可,但是这种方法无法通过 OJ,超时了,所以必须优化这种方法,这种方法重复计算了很多地方,比如要完成一个节点的计算,就得一直找左右子节点计算,可以把已经算过的节点用 HashMap 保存起来,以后递归调用的时候,现在 HashMap 里找,如果存在直接返回,如果不存在,等计算出来后,保存到 HashMap 中再返回,这样方便以后再调用,参见代码如下:

解法一:

class Solution {
public:
int rob(TreeNode* root) {
unordered_map<TreeNode*, int> m;
return dfs(root, m);
}
int dfs(TreeNode *root, unordered_map<TreeNode*, int> &m) {
if (!root) return ;
if (m.count(root)) return m[root];
int val = ;
if (root->left) {
val += dfs(root->left->left, m) + dfs(root->left->right, m);
}
if (root->right) {
val += dfs(root->right->left, m) + dfs(root->right->right, m);
}
val = max(val + root->val, dfs(root->left, m) + dfs(root->right, m));
m[root] = val;
return val;
}
};

下面再来看一种方法,这种方法的递归函数返回一个大小为2的一维数组 res,其中 res[0] 表示不包含当前节点值的最大值,res[1] 表示包含当前值的最大值,那么在遍历某个节点时,首先对其左右子节点调用递归函数,分别得到包含与不包含左子节点值的最大值,和包含于不包含右子节点值的最大值,则当前节点的 res[0] 就是左子节点两种情况的较大值加上右子节点两种情况的较大值,res[1] 就是不包含左子节点值的最大值加上不包含右子节点值的最大值,和当前节点值之和,返回即可,参见代码如下:

解法二:

class Solution {
public:
int rob(TreeNode* root) {
vector<int> res = dfs(root);
return max(res[], res[]);
}
vector<int> dfs(TreeNode *root) {
if (!root) return vector<int>(, );
vector<int> left = dfs(root->left);
vector<int> right = dfs(root->right);
vector<int> res(, );
res[] = max(left[], left[]) + max(right[], right[]);
res[] = left[] + right[] + root->val;
return res;
}
};

下面这种解法由网友 edyyy 提供,仔细看了一下,也非常的巧妙,思路和解法二有些类似。这里的 helper 函数返回当前结点为根结点的最大 rob 的钱数,里面的两个参数l和r表示分别从左子结点和右子结点开始 rob,分别能获得的最大钱数。在递归函数里面,如果当前结点不存在,直接返回0。否则对左右子结点分别调用递归函数,得到l和r。另外还得到四个变量,ll和lr表示左子结点的左右子结点的最大 rob 钱数,rl 和 rr 表示右子结点的最大 rob 钱数。那么最后返回的值其实是两部分的值比较,其中一部分的值是当前的结点值加上 ll, lr, rl, 和 rr 这四个值,这不难理解,因为抢了当前的房屋,则左右两个子结点就不能再抢了,但是再下一层的四个子结点都是可以抢的;另一部分是不抢当前房屋,而是抢其左右两个子结点,即 l+r 的值,返回两个部分的值中的较大值即可,参见代码如下:

解法三:

class Solution {
public:
int rob(TreeNode* root) {
int l = , r = ;
return helper(root, l, r);
}
int helper(TreeNode* node, int& l, int& r) {
if (!node) return ;
int ll = , lr = , rl = , rr = ;
l = helper(node->left, ll, lr);
r = helper(node->right, rl, rr);
return max(node->val + ll + lr + rl + rr, l + r);
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/337

类似题目:

House Robber II

House Robber

参考资料:

https://leetcode.com/problems/house-robber-iii/

https://leetcode.com/problems/house-robber-iii/discuss/79333/Simple-C%2B%2B-solution

https://leetcode.com/problems/house-robber-iii/discuss/79363/Easy-understanding-solution-with-dfs

https://leetcode.com/problems/house-robber-iii/discuss/79330/Step-by-step-tackling-of-the-problem

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] House Robber III 打家劫舍之三的更多相关文章

  1. [LintCode] House Robber III 打家劫舍之三

    The thief has found himself a new place for his thievery again. There is only one entrance to this a ...

  2. [LeetCode] 337. House Robber III 打家劫舍之三

    The thief has found himself a new place for his thievery again. There is only one entrance to this a ...

  3. [LeetCode] 337. House Robber III 打家劫舍 III

    The thief has found himself a new place for his thievery again. There is only one entrance to this a ...

  4. [LeetCode] House Robber II 打家劫舍之二

    Note: This is an extension of House Robber. After robbing those houses on that street, the thief has ...

  5. LeetCode House Robber III

    原题链接在这里:https://leetcode.com/problems/house-robber-iii/ 题目: The thief has found himself a new place ...

  6. [LeetCode] The Maze III 迷宫之三

    There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolli ...

  7. 337 House Robber III 打家劫舍 III

    小偷又发现一个新的可行窃的地点. 这个地区只有一个入口,称为“根”. 除了根部之外,每栋房子有且只有一个父房子. 一番侦察之后,聪明的小偷意识到“这个地方的所有房屋形成了一棵二叉树”. 如果两个直接相 ...

  8. [LeetCode] House Robber 打家劫舍

    You are a professional robber planning to rob houses along a street. Each house has a certain amount ...

  9. Leetcode 337. House Robber III

    337. House Robber III Total Accepted: 18475 Total Submissions: 47725 Difficulty: Medium The thief ha ...

随机推荐

  1. 读书笔记--SQL必知必会05--高级数据过滤

    5.1 组合使用WHERE子句 操作符(operator)也称为逻辑操作符(logical operator),用来联结或改变WHERE子句中的过滤条件. 5.1.1 AND操作符 在WHERE子句中 ...

  2. angularjs和ajax的结合使用 (二)

    今天我们来继续丰富上次的例子.我们来搞些 稍微复杂点的应用. 首先我们来加一个全选 的功能. 上一篇的例子里我们看到 分页时载入的是我们通过linq 查询自定义列 然后构建的匿名类 .使用这种EF框架 ...

  3. angularjs学习使用分享

    angularjs是一个为动态web应用设计的结构框架,它是为了克服html在构建应用上的不足而设计的. 工作原理: 1 加载html,然后解析成DOM: 2 加载angular.js脚本: 3 An ...

  4. ubuntu Chromium 安装 pepperflashplugin

    sudo apt-get update sudo apt-get install chromium-browser sudo apt-get install pepperflashplugin-non ...

  5. C#中级-常用多线程操作(持续更新)

    一.前言       多线程操作一直是编程的常用操作,掌握好基本的操作可以让程序运行的更加有效.本文不求大而全,只是将我自己工作中常常用到的多线程操作做个分类和总结.平时记性不好的时候还能看看.本文参 ...

  6. 配置 EPEL yum 源

    当我们在linux上, 使用yum 安装包时,报错如下: Loaded plugins: product-id, refresh-packagekit, security, subscription- ...

  7. JDBC_part3_批处理_事务_元数据

    本文为博主辛苦总结,希望自己以后返回来看的时候理解更深刻,也希望可以起到帮助初学者的作用. 转载请注明 出自 : luogg的博客园 谢谢配合! JDBC_day03 String a = " ...

  8. 居然是Firefox没有抛弃我们

    面向企业级市场,一款网页浏览器的很多特性不是说改就改,说丢弃就丢弃.就像微软不能抛弃IE一样,Firefox也有类似的定位和使命. Firefox即尝试提供企业级市场所需的特性稳定的软件版本(LTS) ...

  9. 让linux开机默认开启小键盘

     linux默认开机不开启数字键盘numberlock,每次输入开机密码还得劳烦自己去点亮指示灯,让此灯开机自动点亮,需要一个软件才行,就是numlockx了,可以通过yum安装:yuminstall ...

  10. HttpSession与Hibernate中Session的区别

    一.javax.servlet.http.HttpSession是一个抽象接口 它的产生:J2EE的Web程序在运行的时候,会给每一个新的访问者建立一个HttpSession,这个Session是用户 ...