[LeetCode] House Robber III 打家劫舍之三
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
类似题目:
参考资料:
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 打家劫舍之三的更多相关文章
- [LintCode] House Robber III 打家劫舍之三
The thief has found himself a new place for his thievery again. There is only one entrance to this a ...
- [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 ...
- [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 ...
- [LeetCode] House Robber II 打家劫舍之二
Note: This is an extension of House Robber. After robbing those houses on that street, the thief has ...
- LeetCode House Robber III
原题链接在这里:https://leetcode.com/problems/house-robber-iii/ 题目: The thief has found himself a new place ...
- [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 ...
- 337 House Robber III 打家劫舍 III
小偷又发现一个新的可行窃的地点. 这个地区只有一个入口,称为“根”. 除了根部之外,每栋房子有且只有一个父房子. 一番侦察之后,聪明的小偷意识到“这个地方的所有房屋形成了一棵二叉树”. 如果两个直接相 ...
- [LeetCode] House Robber 打家劫舍
You are a professional robber planning to rob houses along a street. Each house has a certain amount ...
- Leetcode 337. House Robber III
337. House Robber III Total Accepted: 18475 Total Submissions: 47725 Difficulty: Medium The thief ha ...
随机推荐
- javascript权威指南笔记
最近每天工作之余看下js的细节部分,时间不是很多,所以看的进度也不会太快,写个博客监督自己每天都看下. 以前不知道的细节或者以前知道但是没注意过的地方都会记录下来,所以适合有一定基础的,不适合零基础新 ...
- ASP.NET Core 中文文档 第四章 MVC(3.4)如何使用表单
原文:Working with Forms 作者:Rick Anderson.Dave Paquette.Jerrie Pelser 翻译:姚阿勇(Dr.Yao) 校对:孟帅洋(书缘) 这篇文章演示了 ...
- 『.NET Core CLI工具文档』(九)dotnet-run
说明:本文是个人翻译文章,由于个人水平有限,有不对的地方请大家帮忙更正. 原文:dotnet-run 翻译:dotnet-run 名称 dotnet-run -- 没有任何明确的编译或启动命令运行&q ...
- c#面向对象基础技能——学习笔记(三)基于OOP思想研究对象的【方法】
实例方法:(解决问题的步骤)完成某功能的各种语句的组合 编写方法要考虑的内容: 1.通过项目需求,确定各方法的任务.功能: 2.方法的可访问性(默认是private):(字段private 属性int ...
- ThreadPool.QueueUserWorkItem的用法
代码: ThreadPool.SetMaxThreads(, ); ThreadPool.QueueUserWorkItem((obj) => { MessageBox.Show("执 ...
- WPF's Style BasedOn
<Style x:Key="BasedStyle" BasedOn="{x:Null}" TargetType="{x:Type Control ...
- android 创建数组
一: private String[] data = new String[]{"Hello", "jike", "world"}; 二: ...
- 消耗战 bzoj 2286
消耗战(2s 512MB)repair [问题描述] 在一场战争中,战场由n个岛屿和n-1个桥梁组成,保证每两个岛屿间有且仅有一条路径可达.现在,我军已经侦查到敌军的总部在编号为1的岛屿,而且他们已经 ...
- 4.5 .net core下直接执行SQL语句并生成DataTable
.net core可以执行SQL语句,但是只能生成强类型的返回结果.例如var blogs = context.Blogs.FromSql("SELECT * FROM dbo.Blogs& ...
- xampp与Hbuilder、phpstorm配置
1.xampp的安装就不用多说了,安装完按之后出现这个界面. 2.点击中间那个按钮,运行三个选项,全部正常之后是这样的,这样xampp就不用管了,但是要记下安装的路径,之后需要用 3.首先说Hbuil ...