leetcode——337—— House Robber III
来源:互联网 发布:java.util.optional 编辑:程序博客网 时间:2024/06/08 04:36
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 1Maximum 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.
递归函数返回一个大小为2的一维数组res,其中res[0]表示抢劫当前节点值的最大值,res[1]表示不抢劫当前节点的最大值,那么我们在遍历某个节点时,首先对其左右子节点调用递归函数,分别得到包含与不包含左子节点值的最大值,和包含于不包含右子节点值的最大值,那么当前节点的res[1]就是左子节点两种情况的较大值加上右子节点两种情况的较大值,res[0]就是不包含左子节点值的最大值加上不包含右子节点值的最大值,和当前节点值之和,返回即可
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int rob(TreeNode* root) { vector<int> res=dfs(root); return max(res[0],res[1]); } vector<int> dfs(TreeNode *root){ vector<int> res(2,0);//0 存储robed 最大利益, 1,nonrobed 最大利益 if(!root) return res; vector<int> lres=dfs(root->left); vector<int> rres=dfs(root->right); res[0]=lres[1]+rres[1]+root->val; res[1]=max(lres[0],lres[1])+max(rres[0],rres[1]); return res; } };
0 0
- LeetCode题解——House Robber III
- leetcode——337—— House Robber III
- House Robber III——Difficulty:Medium
- LeetCode——House Robber
- LeetCode——House Robber
- LeetCode——House Robber
- leetcode 337:House Robber III
- LeetCode 337 House Robber III
- 337 leetcode 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 House Robber III
- [LeetCode] House Robber III
- leetcode---House Robber III
- 《leetCode》:House Robber III
- js跨域访问,No ‘Access-Control-Allow-Origin‘ header is present on
- Linux网络编程入门
- JQuery中Ajax实现对Map,List集合数据的接收
- iOS开发-取消导航栏渲染问题(适应各种渲染问题)
- JAVA面试题二--转载自用
- leetcode——337—— House Robber III
- jcenter 的一点总结
- hdu 5667
- Spring Junit4 测试Web应用程序
- Ubuntu下rm;rmdir;rm -rf;学习
- windows下安装配置apache服务器
- ORA-12516: TNS: 监听程序无法找到匹配协议栈的可用句柄
- java.lang.NoClassDefFoundError: org/apache/log4j/spi/NOPLoggerRepository
- jquery 的(function(){});表示什么?