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 呀! 和大家一起刷题不快不慢,没想到已经进行到了第二阶段,「动态规划」这部分题目很难,而且很不容易理解,目前我的题目做了一半,凭着之前对于「动态规划」的理解和最近做的题目做 ...
随机推荐
- web 页面上纯js实现按钮倒计数功能(实时计时器也可以)
需求构思:本功能想实现的是,一个按钮在页面载入就显示提醒续费,,,倒数60秒后,完成提醒功能,可以按另外一个页面跳转到主页. 参考网上的大神,实现如下:Button2倒数,Button3跳转,在页面上 ...
- kafka consumer重复消费问题
在做分布式编译的时候,每一个worker都有一个consumer,适用的kafka+zookeep的配置都是默认的配置,在消息比较少的情况下,每一个consumer都能均匀得到互不相同的消息,但是当消 ...
- ionic3 自定义组件 滑动选择器 ion-multi-picker
1.ionic3中有一个 ion-datatime 给大家选择时间提供了一个很方便的组件 效果如图 链接 https://ionicframework.com/docs/api/component ...
- Collection集合的三种初始化方法
(一) java容器可以分为两大类 1)Collection其中包括List,Set,Queue 2)Map (二) Arrays.asList()方法:接受一个数组或一个逗号分隔的元素列表,并将其转 ...
- 利用htmlparser读取html文档的内容
1.添加相关的的jar htmlparser-2.1.jar 2.方法和代码 public static String readHtml(File html) { String htmlPath = ...
- ECB cspk7 加密
public function test(){ $param = input('param.'); // $input = 'userid=7&gameid=100107&buycou ...
- activity select problem(greedy algorithms)
many activities will use the same place, every activity ai has its' start time si and finish time f ...
- 启动tomcat报错Status 状态为 Deployment failed
- 小妖精的完美游戏教室——东方project,同人,自机
//================================================================ //// Copyright (C)// All Rights R ...
- 利用开源项目jadx反编译Android应用
原文转自:http://bbs.itheima.com/thread-200475-1-1.html 利用开源项目jadx反编译Android应用 利用Github开源项目jadx可以直接对 .dex ...