Friday, April 22, 2016

337. House Robber III

The thief has found himself a new place for his thievery again. There is only one entrance to this area, called 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 form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night.

Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police.

 

Example 1:

Input: root = [3,2,3,null,3,null,1]
Output: 7
Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.

Example 2:

Input: root = [3,4,5,1,3,null,1]
Output: 9
Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.

 

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • 0 <= Node.val <= 104
A:

首先:就是遍历一遍。然后考虑2种情况。 取或者不取 node
        先考虑        递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int rob(TreeNode* root) {
return helper(root, true);
}
private:
int helper(TreeNode* root, bool canUseRoot){
if(!root)
return 0;
int noRoot = helper(root->left, true)+ helper(root->right, true);
if(canUseRoot){
int useRoot = root->val+ helper(root->left, false) + helper(root->right, false);
return max(useRoot, noRoot);
}else{
return noRoot;
}
}
};


可以预期的, LTE了。 
这里有大量的重复计算。

要防止多次(重复)遍历。 有个简单的方法,就是用hash. 这里,我们用hashMap来保存结果

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int rob(TreeNode* root) {
if(!root)
return 0;
auto it = map.find(root);
if(it != map.end()){
return it->second;
}else{
int noUse = rob(root->left) + rob(root->right);
int useRoot = root->val +
(root->left? rob(root->left->left) + rob(root->left->right) : 0 ) +
(root->right? rob(root->right->left) + rob(root->right->right) :0);
map[root] = max(noUse, useRoot);
return map[root];
}
}
unordered_map<TreeNode*, int> map; //use or not use, what it can rob
};


Mistakes:
1:  withRoot 计算的时候, 三目运算符, 要括起来。  





No comments:

Post a Comment