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);
        }
    };
  • 相关阅读:
    Oracle通过Rman的"copy datafile"转移数据文件后不要使用sqlplus来重命名文件位置和文件名
    Oracle使用errorstack跟踪客户端的ORA报错
    Oracle OEM 13C表空间报警延迟问题
    CH5 用神经网络解决线性问题
    CH4 简化神经网络模型
    CH3 初识 TensorFlow
    Python 语言和 TensorFlow 框架环境准备
    创建型模式之单例模式与工厂模式(一)
    Node.js Koa框架学习笔记
    国庆七天假 不如来学学Vue-Router
  • 原文地址:https://www.cnblogs.com/zhoudayang/p/5279889.html
Copyright © 2011-2022 走看看