zoukankan      html  css  js  c++  java
  • 337. House Robber III

    The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night.

    Determine the maximum amount of money the thief can rob tonight without alerting the police.

    Example 1:

         3

        /

    2   3

      

         3   1

    Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.

    Example 2:

    3

        /

       4   5

      /   

     13   1

    Maximum amount of money the thief can rob = 4 + 5 = 9.

    Credits:
    Special thanks to @dietpepsi for adding this problem and creating all test cases.

    Subscribe to see which companies asked this question

        思路,dfs。递归函数返回两个值,分别是窃取root节点和不窃取root节点时窃取的资金总额。当根节点为空时,直接返回(0,0).根节点不为空的时候,窃取根节点的时候,窃取的资金为left.second+right.second+root->val(此时,不能窃取根节点左右子结点).而不窃取根节点的时候,窃取的资金为max(left.first,left.second)+max(right.first,right.second),即左右子节点能够窃取的最大值之和。

        最终,在实际调用完成之后,我们返回窃取root节点和不窃取root节点偷得的资金的最大值。

    /**
     * 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 {
    pair<int,int> help(TreeNode *root){
        if(!root){
            return make_pair(0,0);
        }
        auto left = help(root->left);
        auto right = help(root->right);
        //窃取root节点
        int rob_root = left.second+right.second +root->val;
        //不窃取root节点
        int not_rob_root = max(left.first,left.second)+max(right.first,right.second);
        return make_pair(rob_root,not_rob_root);
    }
    public:
        int rob(TreeNode* root) {
            auto result =help(root);
            return max(result.first,result.second);
        }
    };
  • 相关阅读:
    HDU6301 SET集合的应用 贪心
    线段树与树状数组的对比应用
    树状数组
    JDBC链接MySQL数据库
    HDU4686Arc of Dream 矩阵快速幂
    HDU1757矩阵快速幂
    B1013. 数素数 (20)
    B1023. 组个最小数 (20)
    [教材]B1020. 月饼 (25)
    [教材]A1025. PAT Ranking (25)
  • 原文地址:https://www.cnblogs.com/zhoudayang/p/5279889.html
Copyright © 2011-2022 走看看