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 };
  • 相关阅读:
    SDWebImage内存性能优化
    dataGridView1数据导出
    listView数据导出
    sqlserver定时备份
    C#-IniFiles文件配置连接数据库
    (转)线程同步详解
    C#工具类:Json操作帮助类(转载)
    c#实现验证码功能
    屏蔽F12审查元素,禁止使用右键菜单
    c# excel如何导入到sqlserver数据库
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5708671.html
Copyright © 2011-2022 走看看