[leetcode]337. House Robber III
来源:互联网 发布:scratch少儿趣味编程2 编辑:程序博客网 时间:2024/05/02 08:57
题目链接:https://leetcode.com/problems/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 1Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
3 / \ 4 5 / \ \ 1 3 1Maximum amount of money the thief can rob = 4 + 5 = 9.
解题思路:动态规划,深度优先遍历二叉树。假设在root节点在L层,那么有两种情况。一:取root的值,root左节点和右节点不取;二:不取root节点,root的左节点和右节点可取可不取。通过记录每个节点取与不取得到的最大钱数,最后返回两个数中最大值。
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); if(root==NULL) return res; vector<int> left=dfs(root->left); vector<int> right=dfs(root->right); res[0]=left[1]+right[1]+root->val; res[1]=max(left[0],left[1])+max(right[0],right[1]); 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
- 蓝桥杯-入门训练 Fibonacci数列
- 算法竞赛入门经典 第二版 习题4-2 正方形 Squares uva201
- Linux内核工程导论——linux学习和职业曲线
- JZOJ4954. 【WC模拟】Equation
- Erlang(12):进程和错误
- [leetcode]337. House Robber III
- 机器学习(1)--模型评估与选择
- Intersection of Two Linked Lists
- LeetCode 415. Add Strings
- leetcode128--longest consecutive sequence(java)
- REST 架构该怎么生动地理解
- Jenkins+ Gradle +Lint对Android工程源码进行静态代码分析
- php菜鸟日记1
- MFC ComboBox控件中EditChange无反应