LeetCode No.337 House Robber III
来源:互联网 发布:json格式用什么打开 编辑:程序博客网 时间:2024/05/24 06:35
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.
====================================================================================================================================
这道题目跟leetcode198题的意思差不多,只是多了一个条件。其大意是:一个小偷要去一条(二叉树形)街道偷东西,每间房子都有一定数量的金钱,但小偷不能偷任意相连的两间房子的金钱,不然就会触发警报系统。求小偷在不触发警报系统情况下能偷到的最大金额。
对于每一个节点,我们都有两种处理方式,即偷与不偷。用ans[0]表示不偷该节点,ans[1]表示偷该节点,则有
ans[0] = max ( left[0] , left[1] ) + max ( right[0] , right[1] ) ;// ans[0] doesn't contains the rootans[1] = root -> val + left[0] + right[0] ; // ans[1] contains the root
附上代码:
/** * 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> ans = BinarySearch ( root ) ; return max ( ans[0] , ans[1] ) ; } vector <int> BinarySearch ( TreeNode* root ) { if ( root == NULL ) return vector <int> ( 2 , 0 ) ; vector <int> left = BinarySearch ( root -> left ) ; vector <int> right = BinarySearch ( root -> right ) ; vector <int> ans ( 2 , 0 ) ; ans[0] = max ( left[0] , left[1] ) + max ( right[0] , right[1] ) ;// ans[0] doesn't contains the root ans[1] = root -> val + left[0] + right[0] ; // ans[1] contains the root return ans ; }};
- LeetCode No.337 House Robber III
- 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 No.337. House Robber III
- LeetCode House Robber III
- [LeetCode] House Robber III
- leetcode---House Robber III
- 《leetCode》:House Robber III
- [LeetCode]House Robber III
- [leetcode] House Robber III
- leetcode House Robber III
- LeetCode:House Robber III
- Windows Pe 第三章 PE头文件-EX-相关编程-1(PE头内容获取)
- Codeforces Round #359 (Div. 2)E. Optimal Point ★ ★ ★
- node使用记录
- 贪心算法正确性证明
- Atmosphere框架--网页聊天
- LeetCode No.337 House Robber III
- QAQ的区间统计
- STM32开发环境(2)----如何完成工程构建
- centOS 7 lamp环境搭建&&php7.0的安装
- c++单元测试gtest
- 计算机里的概念,技巧与工具
- Windows Pe 第三章 PE头文件-EX-相关编程-2(RVA_FOA转换)
- super && this 关键字 && try catch
- JAVA并发编程-LOCK锁