天天看點

LeetCode_337. House Robber III

題目描述:

LeetCode_337. House Robber III

思路1:暴力求解。目前節點能偷到的最大錢數有兩種可能的計算方式。1.爺爺節點和孫子節點偷的錢的總和 2.兒子節點偷的錢的總和。則目前節點能偷到的最大錢數隻要取一個max即可。

/**
 * 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) {
        if(root==NULL)
            return 0;
        int money=root->val;
        if(root->left){
            money+=rob(root->left->left)+rob(root->left->right);
        }
        if(root->right){
            money+=rob(root->right->left)+rob(root->right->right);
        }
        return max(money,rob(root->left)+rob(root->right));
    }
};      

時間複雜度太高,逾時。

思路2:帶有備忘錄的周遊

/**
 * 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) {
        if(root==NULL)
            return 0;
        if(mp.find(root)!=mp.end())
            return mp[root];
        int money=root->val;
        if(root->left){
            money+=rob(root->left->left)+rob(root->left->right);
        }
        if(root->right){
            money+=rob(root->right->left)+rob(root->right->right);
        }
        mp.insert(make_pair(root,max(money,rob(root->left)+rob(root->right))));
        return mp[root];
    }
private:
    map<TreeNode*,int> mp;
};      
/**
 * 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) {
        if(root==NULL)
            return 0;
        vector<int> steal(2,0);
        helper(root,steal);
        return max(steal[0],steal[1]);
    }
    void helper(TreeNode* root,vector<int>& steal){
        if(root==NULL)
            return ;
        vector<int> left(2,0);
        vector<int> right(2,0);
        helper(root->left,left);
        helper(root->right,right);
        steal[0]=max(left[0],left[1])+max(right[0],right[1]);
        steal[1]=left[0]+right[0]+root->val;
    }
};      

繼續閱讀