[LeetCode] 337. House Robber III
来源:互联网 发布:什么软件可以做动漫 编辑:程序博客网 时间:2024/06/05 00:51
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.
// useless(pretty slow) but clear int rob(TreeNode* root) { if (root == nullptr) return 0; int ll, lr , rl, rr, l, r; ll = lr = rl = rr = l = r = 0; if (root->left) { ll = rob(root->left->left); lr = rob(root->left->right); } if (root->right) { rl = rob(root->right->left); rr = rob(root->right->right); } l = rob(root->left); r = rob(root->right); return max(root->val + ll + lr + rl + rr, l + r); }
// using unordered_map to hash calculated resultclass Solution {public: int rob(TreeNode* root) { unordered_map<TreeNode *, int> map; return __rob(root, map); }private: int __rob(TreeNode *root, unordered_map<TreeNode *, int> &map) { if (root == nullptr) return 0; if (map.find(root) != map.end()) return map[root]; int ll, lr , rl, rr, l, r; ll = lr = rl = rr = l = r = 0; if (root->left) { ll = __rob(root->left->left, map); lr = __rob(root->left->right, map); } if (root->right) { rl = __rob(root->right->left, map); rr = __rob(root->right->right, map); } l = __rob(root->left, map); r = __rob(root->right, map); int res = max(root->val + ll + lr + rl + rr, l + r); map[root] = res; return res; }};
阅读全文
0 0
- [leetcode] 337. House Robber III
- LeetCode#337. House Robber III
- LeetCode *** 337. House Robber III
- [leetcode]337. House Robber III
- LeetCode-337. House Robber III
- [leetcode]337. House Robber III
- LeetCode-337.House Robber III
- LeetCode 337. House Robber III
- Leetcode 337. House Robber III
- leetcode 337. House Robber III
- LeetCode - 337. House Robber III
- 【LeetCode】337. House Robber III
- 【leetcode】337. House Robber III
- [leetcode] 337. House Robber III
- LeetCode 337. House Robber III
- 【LeetCode】337. House Robber III
- LeetCode 337. House Robber III
- LeetCode 337. House Robber III
- 微信开发基本消息回复
- Wiki 人工智能 深度学习 TensorFlow 下载与安装
- LeetCode周练Contest-38代码解析(C++)
- HTTP基础知识
- 高效的遍历cmap中的元素方法
- [LeetCode] 337. House Robber III
- c#方法的重载和重写
- 关于idea基础的常用快捷键
- 超详细的pxe实现系统自动安装的图文说明————设置主机名和静态IP
- 什么是TLB
- React Native优秀的第三方插件(Android & iOS)
- 【备忘】潭州学院2017年网络营销65期初级班+高级班(视频教程)
- ubuntu16.04搭建lamp环境(Apache2+PHP7.0+MySQL5.7)
- redis中的map存储大量数据会有什么问题