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 res;
        res = subRob(root);
        return max(res[0], res[1]);
    }
    
    vector subRob(TreeNode* node)
    {
        if (node == NULL)
            return vector{0, 0};
        vector left = subRob(node->left);
        vector right = subRob(node->right);
        vector 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;
    }
};

你可能感兴趣的:(House Robber III)