/**
* 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. Msfvenom学习总结

    1.    –p (- -payload-options) 添加载荷payload. 载荷这个东西比较多,这个软件就是根据对应的载荷payload生成对应平台下的后门,所以只有选对payload,再填 ...

  2. Dilated Convolutions 空洞卷积

    Dilated Convolutions,中文一般称为空洞卷积或者扩张卷积,是一种改进的图像卷积方法. 扩张卷积工作示意图如下: 图a是普通的卷积,感受野是3*3,相当于扩充dilation=0 图b ...

  3. Visual Studio AI 离线模型训练(Windows10)

    一.序 环境搭建:[查看] samples-for-ai项目下载:[下载],两个版本,一个2018年6月15日前,一个2018年6月15日-16日版本(当前最新版本). 在环境搭建过程中,通过git ...

  4. Arch Linux root密码忘记了怎么办

    https://wiki.archlinux.org/index.php/Reset_root_password_(简体中文)https://wiki.archlinux.org/index.php/ ...

  5. s2第二章深入c#类型

    S2第二章预习笔记  深入c# 数据类型 常用类型      java     c#     举例 整形          int     int     年龄 浮点型        float    ...

  6. 为git服务器配置gitosis管理权限

    yum install python-setuptools git clone https://github.com/tv42/gitosis.git cd gitosis sudo python s ...

  7. Unix中共享信息方式

  8. Django学习笔记之数据库-QuerySet_API

    QuerySet API 我们通常做查询操作的时候,都是通过模型名字.objects的方式进行操作.其实模型名字.objects是一个django.db.models.manager.Manager对 ...

  9. Tomcat虚拟根目录与虚拟目录

    tomcat版本:apache-tomcat-7.0.42 参考:http://blog.csdn.net/pangdingshan/article/details/7214786 一.虚拟根目录 1 ...

  10. HTTP各种特性

    一.Http客户端 1.浏览器.打开百度首页 2.Curl工具 二.CORS 跨域(浏览器的功能) 1.修改Server.js const http = require('http'); const ...