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 };
  • 相关阅读:
    Windows8.1 + Nvidia cuda8.0 + Vs2015
    读《鲜花帝国》有感
    oracle-sql书写
    oracle--聚合函数和case when结合使用
    oracle正则表达式
    oracle中case when使用
    oracle分区表之列表分区
    linux下oracl字符集修改(WE8ISO8859P1 --> ZHS16GBK)
    linux 下安装oracle数据库
    oracle学习笔记
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5708671.html
Copyright © 2011-2022 走看看