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 };
  • 相关阅读:
    rsync 安装使用详解
    shell全备份脚本(借鉴别人的,在其基础上修复完善了bug)
    完全备份、差异备份以及增量备份的区别
    云主机格式化和挂载数据盘
    JSONP跨域
    php的多线程使用
    tp其他功能
    Zend Guard Loader和Zend Optimizer的安装(更新中)
    前端编码规范
    前端优化
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5708671.html
Copyright © 2011-2022 走看看