House Robber III

題目來源
還是房屋搶劫的問題,不過這次改成了二叉樹搶劫。
然后我不會!!!
看了下答案,最簡單的方法就是比較所有情況,深度搜索。
代碼如下:

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

這種時間復雜度比較高。然后進一步的改進方法呢,實際上用到了DP。

/**
 * 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> res;
        res = subRob(root);
        return max(res[0], res[1]);
    }
    
    vector<int> subRob(TreeNode* node)
    {
        if (node == NULL)
            return vector<int>{0, 0};
        vector<int> left = subRob(node->left);
        vector<int> right = subRob(node->right);
        vector<int> res(2, 0);
        res[0] = max(left[0], left[1]) + max(right[0], right[1]);
        res[1] = node->val + left[0] + right[0];
        return res;
    }
};
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容