您的位置:首页 > 其它

LeetCode#337. House Robber III

2016-03-16 12:56 337 查看
337. House Robber III

Total Accepted: 2052 Total Submissions: 5607 Difficulty: Medium

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.2052 Total Submissions: 5607 Difficulty: Medium

解题思路

(1)DFS:深度优先搜索

(2)递归函数返回两个值,分别是窃取root节点和不窃取root节点时窃取的资金总额。

当根节点为空时,直接返回(0,0).

根节点不为空的时候,窃取根节点的时候,窃取的资金为left[0] + right[0] + root->val(此时,不能窃取根节点左右子结点).

而不窃取根节点的时候,窃取的资金为max(left[0], left[1]) + max(right[0], right[1]),即左右子节点能够窃取的最大值之和。

(3)最终我们返回窃取root节点和不窃取root节点偷得的资金的最大值。

C++代码

/**
* 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 = dfs(root);
return max(ans[0], ans[1]);
}
vector<int> dfs(TreeNode *root) {
if (!root) return vector<int>(2, 0);//当前根节点为空
vector<int> left = dfs(root->left);//递归深度优先搜索左子树
vector<int> right = dfs(root->right);//递归深度优先搜索右子树
vector<int> ans(2, 0);
ans[0] = max(left[0], left[1]) + max(right[0], right[1]);
ans[1] = left[0] + right[0] + root->val;
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息