/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int Rob(TreeNode root)
{
int[] num = dfs(root);
return Math.Max(num[], num[]);
} private int[] dfs(TreeNode x)
{
if (x == null) return new int[];
int[] left = dfs(x.left);
int[] right = dfs(x.right);
int[] res = new int[];
res[] = left[] + right[] + x.val;
res[] = Math.Max(left[], left[]) + Math.Max(right[], right[]);
return res;
}
}

https://leetcode.com/problems/house-robber-iii/#/description

补充一个python的实现:

 class Solution:
def dfs(self,root):
if root==None:
return [0,0]#空节点
counter = [0,0]
left = self.dfs(root.left)
right = self.dfs(root.right) #取当前节点,则其左右子节点都不能取
counter[0] = root.val + left[1] + right[1] #不取当前节点,则左右子节点是否选取要看子节点选择是否更大
counter[1] = max(left[0],left[1]) + max(right[0],right[1])
return counter def rob(self, root: 'TreeNode') -> 'int':
result = self.dfs(root)
#第一位表示取当前节点的累计值,第二位表示不取当前节点的累计值
return max(result[0],result[1])

leetcode337的更多相关文章

  1. [Swift]LeetCode337. 打家劫舍 III | House Robber III

    The thief has found himself a new place for his thievery again. There is only one entrance to this a ...

  2. Leetcode337. 打家劫舍 III

    Leetcode 337. 打家劫舍 III 在上次打劫完一条街道之后和一圈房屋后,小偷又发现了一个新的可行窃的地区.这个地区只有一个入口,我们称之为"根". 除了"根& ...

  3. LeetCode 337

    House Robber III The thief has found himself a new place for his thievery again. There is only one e ...

  4. 终拿字节Offer...动态规划复盘...

    大家好!我是 Johngo 呀! 和大家一起刷题不快不慢,没想到已经进行到了第二阶段,「动态规划」这部分题目很难,而且很不容易理解,目前我的题目做了一半,凭着之前对于「动态规划」的理解和最近做的题目做 ...

随机推荐

  1. 配置selenium grid

    本文对Selenium Grid进行了完整的介绍,从环境准备到使用Selenium Grid进行一次完整的多节点分布式测试. 运行环境为Windows 10,Selenium版本为 3.5.0,Chr ...

  2. 一分钟学会ConstraintLayout(转载)

    原文地址:https://www.v2ex.com/t/287863 最近更新了Android Studio,突然发现xml中的布局已经变成了ConstraintLayout,于是搜了一篇文章看一下 ...

  3. @MapperScan使用

    @MapperScan:要扫描mapper类包的路径 还可以扫描多个包,如: @MapperScan({"com.kfit.demo","com.kfit.user&qu ...

  4. itextsharp报错PdfReader not opened with owner password

    itextSharp读取Pdf时报错:PdfReader not opened with owner password 报错原因:pdf文件被用户加密了. 解决办法:在创建pdfReader实例后,加 ...

  5. locate语法

    1.命令格式:locate [参数] [文件] 2.命令功能:locate命令可以在搜寻数据库时快速找到档案,数据库由updatedb程序来更新,updatedb是由cron daemon周期性建立的 ...

  6. usermod语法

    语法 usermod [-LU][-c <备注>][-d <登入目录>][-e <有效期限>][-f <缓冲天数>][-g <群组>][-G ...

  7. echarts双y轴折线图柱状图混合实时更新图

    先看下效果,自己用ps做了张gif图,发现很好玩啊..不喜勿喷 自己下载个echarts.min.js 直接上代码: <!DOCTYPE html><html><head ...

  8. CentOS6.5安装mysql5.7

    CentOS6.5安装mysql5.7 查看mysql的安装路径: [root@bogon ~]# whereis mysql mysql: /usr/bin/mysql /usr/lib/mysql ...

  9. solr实现动态加载分词

    版本是5.3.0 在core(自己创建的模块)的schema.xml里面增加类型: <fieldType name="text_lj" class="solr.Te ...

  10. fixed 相对于父容器定位

    当一个元素设置为 fixed 或 absolute,不设置 top, left 则会在原位置,而脱离文档流,别的元素可以存在于它之后. 而当使用 fixed 后还想相对于父容器进行定位,或者说在当前位 ...