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