leetcode337
/**
* 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的更多相关文章
- [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 ...
- Leetcode337. 打家劫舍 III
Leetcode 337. 打家劫舍 III 在上次打劫完一条街道之后和一圈房屋后,小偷又发现了一个新的可行窃的地区.这个地区只有一个入口,我们称之为"根". 除了"根& ...
- LeetCode 337
House Robber III The thief has found himself a new place for his thievery again. There is only one e ...
- 终拿字节Offer...动态规划复盘...
大家好!我是 Johngo 呀! 和大家一起刷题不快不慢,没想到已经进行到了第二阶段,「动态规划」这部分题目很难,而且很不容易理解,目前我的题目做了一半,凭着之前对于「动态规划」的理解和最近做的题目做 ...
随机推荐
- ADV7482&TP2825开发之总结
ADV7482&TP2825开发之总结 这一两个月在项目里接触到了两个视频解码芯片,主要是使用了两颗芯片的CVBS(NTSC)解码功能.外接CVBS Video接入解码芯片,芯片8位并行输出端 ...
- mail语法
在Linux系统下mail命令的用法 在Linux系统下mail命令的测试 1. 最简单的一个例子: mail -s test admin@aispider.com 这条命令的结果是发一封标题为tes ...
- Windows10 VS2017 C++信号处理
#include "pch.h" #include <iostream> #include <csignal> #include <windows.h ...
- ubuntu 部署 wiki.js
1. 安装node (还是官网的东西靠谱,虽然是english) https://github.com/nodesource/distributions/blob/master/README.md ...
- Windows 应用商店无法下载---启动更新
今天想在应用商店下载东西,但是以直没成功,查看原因结果是因为我的Windows自动更新关了. 百度,如何打开自动更新,要打开本地组策略编辑器,但是我是Windows家庭版,,,没有这个东西,, 最后, ...
- pycharm 设置参数,快捷键
pycharm 设置参数 当编写代码的时候出现红色下划线提示,表示有异常,此时需要导入此模块 参数设置 设置完参数之后执行一下看看效果 这里面0为脚本本身,1为刚才设置的参数hello 快捷键设置 常 ...
- [转]Golang TLS
首先是自签证书: openssl与数字证书的使用 https://blog.csdn.net/yue7603835/article/details/72569012 Golang TLS服务端/客户端 ...
- manhattan plots in qqplot2
###manhattan plots in qqplot2library(ggplot2)setwd("~/ncbi/zm/XPCLR/")read.table("LW. ...
- Unity Mathf/Math数学运算函数说明全集(Chinar总结)
Unity Mathf 数学函数库 本文提供全流程,中文翻译. Chinar 坚持将简单的生活方式,带给世人!(拥有更好的阅读体验 -- 高分辨率用户请根据需求调整网页缩放比例) Chinar -- ...
- 测试那些事儿—软测必备的Linux知识(二)
linux常用命令 用户登录linux后,可以在Linux的命令提示符后面输入命令与系统进行交互. 1.磁盘管理 1.1 cd 切换目录:让登录用户在不同的目录间切换 常用的目录切换 cd~ 进入当前 ...