337. House Robber III
来源:互联网 发布:开票软件金税盘未响应 编辑:程序博客网 时间:2024/06/05 14:31
题目描述:
he 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.
题目要求我们求出一个二叉树不相邻元素的和的最大值。首先,对于一个节点。有取和不取两种选择,如果取,则它的两个儿子不能被取。如果不取,则两个儿子可取可不取。代码如下:/** * 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 { vector<int> getMoney(TreeNode* node) { vector<int> ret(2, 0); if(!node) return ret; vector<int> lRet = getMoney(node->left); vector<int> rRet = getMoney(node->right); ret[0] = lRet[1] + rRet[1] + node->val; ret[1] = max(lRet[0], lRet[1]) + max(rRet[0], rRet[1]); return ret; } public: int rob(TreeNode* root) { vector<int> ret = getMoney(root); return max(ret[0], ret[1]); } };
0 0
- 337. House Robber III
- 337. House Robber III
- 337. House Robber III
- 337. House Robber III
- 337. House Robber III
- 337. House Robber III
- 337. House Robber III
- 337. House Robber III
- 337. House Robber III
- 337. House Robber III
- 337. House Robber III
- 337. House Robber III
- 337. House Robber III
- 337. House Robber III
- 337. House Robber III
- 337. House Robber III
- 337. House Robber III**
- 337. House Robber III
- ISE调用Notepad++的方法
- 【Unity3D UGUI】事件接口(三) 按下移动、释放
- 没有IP地址的主机如何保持IP层联通
- 冒泡排序【改进】
- python装饰器使用例子
- 337. House Robber III
- 单链表的逆转
- |poj 1961|KMP|Period
- Hibernate 学习教程
- 十五、Mysql 分组查询
- C. Functions again-最长连续子序列
- 浏览器拦截跨域请求处理方法(同源策略不允许读取服务器远程资源)
- [数据库学习SQLSERVER] 学习笔记
- 八、分组函数/聚合函数/双行处理函数