• 打家劫舍|||


    题目链接:https://leetcode-cn.com/problems/house-robber-iii
    题目描述:
    在上次打劫完一条街道之后和一圈房屋后,小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为“根”。 除了“根”之外,每栋房子有且只有一个“父“房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 如果两个直接相连的房子在同一天晚上被打劫,房屋将自动报警。
    计算在不触动警报的情况下,小偷一晚能够盗取的最高金额。

    题解:
    方法一:记忆化迭代

    class Solution {
    public:
        int rob(TreeNode* root) {
            unordered_map<TreeNode* , int> umap; // 记录计算过的结果
            if(root == nullptr) return 0;
            if(root->left == nullptr && root->right == nullptr) return root->val;
            if (umap[root]) return umap[root]; // 如果umap里已经有记录则直接返回
            int ans1 = root->val;
            if(root->right)
                ans1 += rob(root->right->left) + rob(root->right->right);
            if(root->left)
                ans1 += rob(root->left->left) + rob(root->left->right);
            int ans2 = rob(root->left) + rob(root->right);
            umap[root] = max(ans1, ans2); // umap记录一下结果
            return max(ans1, ans2);
    
        }
    };
    

    方法二:动态规划
    解题链接:打家劫舍|||题解

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
     *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
     *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
     * };
     */
    class Solution {
    public:
        int rob(TreeNode* root) {
            vector<int> result = robTree(root);
            return max(result[0], result[1]);
        }
        // 长度为2的数组,0:不偷,1:偷
        vector<int> robTree(TreeNode* cur) {
            if (cur == NULL) return vector<int>{0, 0};
            vector<int> left = robTree(cur->left);
            vector<int> right = robTree(cur->right);
            // 偷cur
            int val1 = cur->val + left[0] + right[0];
            // 不偷cur
            int val2 = max(left[0], left[1]) + max(right[0], right[1]);
            return {val2, val1};
        }
    };
    
  • 相关阅读:
    hdu 4308(bfs)
    数位dp
    hdu 4548(素数打表)
    不要把时间浪费在QQ上
    用插值方法构造多项式证明中值问题
    《摩诃般若波罗蜜多心经》 玄奘 译
    证明高斯引理
    《摩诃般若波罗蜜多心经》 玄奘 译
    若一整系数$n$次多项式在有理数域可约,则总可以分解成次数小于$n$的两整系数多项式之积.
    用teamviewer控制内网计算机
  • 原文地址:https://www.cnblogs.com/ZigHello/p/15189018.html
Copyright © 2020-2023  润新知