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

    337. House Robber III

    • Total Accepted: 18475
    • Total Submissions: 47725
    • Difficulty: Medium

    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
      /     
     1   3   1

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

    思路:基本思路和Leetcode 198. House Robber相同,只是将传递公式植入到二叉树的DFS过程中。

    代码:

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     void rob(TreeNode* root,int& pre,int& cur){
    13         if(!root) return;
    14         int lpre=0,lcur=0,rpre=0,rcur=0;
    15         rob(root->left,lpre,lcur);
    16         rob(root->right,rpre,rcur);
    17         pre=lcur+rcur;
    18         cur=max(lpre+rpre+root->val,pre);
    19     }
    20     int rob(TreeNode* root) {
    21         int pre=0,cur=0;
    22         rob(root,pre,cur);
    23         return max(pre,cur);
    24     }
    25 };
  • 相关阅读:
    js获取多选框选择的值并拼接成字符串
    把不可枚举数组转换成可枚举数组
    js对接图片上传接口
    填数字游戏解题机
    带你深入了解nginx基本登录认证(包含配置步骤)
    高三whk回忆录
    SpringBoot异步任务
    Shell 脚本
    【Ubuntu】知识点及经验
    【Ubuntu】 安装相关
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5708671.html
Copyright © 2011-2022 走看看