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;
};

思路3:只需要申请两个变量,用来表示偷或者不偷。状态转移方程就是:
当前节点选择不偷: 当前节点能偷到的最大钱数 = 左孩子能偷到的钱 + 右孩子能偷到的钱
当前节点选择偷: 当前节点能偷到的最大钱数 = 左孩子选择自己不偷时能得到的钱 + 右孩子选择不偷时能得到的钱 + 当前节点的钱数

steal[0]=max(left[0],left[1])+max(right[0],right[1]);
steal[1]=left[0]+right[0]+root->val;

/**
 * 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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章