1.题目告诉我们相邻的两个父子节点不能同时被偷取,求出最大能偷取的金额。
2.这个题目是典型的树形DP,我们定义了两个DP,一个是被偷取的DP1,一个是不偷取的DP2。然后进行深度优先搜索,计算每一个节点的DP1和DP2,最后输出根节点中DP1和DP2的较大者。
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 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.Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
AC代码:
/** * 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: map<TreeNode*,int> dp1; map<TreeNode*,int> dp2; int rob(TreeNode* root) { dfs(root); return max(dp1[root],dp2[root]); } void dfs(TreeNode* root) { if(root == NULL) return; dfs(root->left); dfs(root->right); //偷这个节点 dp1[root]=root->val+dp2[root->left]+dp2[root->right]; //不偷这个节点 dp2[root]=max(max(dp1[root->left]+dp1[root->right],dp2[root->left]+dp2[root->right]), max(dp2[root->left]+dp1[root->right],dp1[root->left]+dp2[root->right])); } };