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 呀! 和大家一起刷题不快不慢,没想到已经进行到了第二阶段,「动态规划」这部分题目很难,而且很不容易理解,目前我的题目做了一半,凭着之前对于「动态规划」的理解和最近做的题目做 ...
随机推荐
- 剑指Offer 30. 连续子数组的最大和 (数组)
题目描述 HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学.今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决.但是,如果向量 ...
- git创建分支并上传仓库
1. 新建分支 xxx 2. git pull (目录下 命令行将线上分支拉倒本地) 3. git checkout xxx (切换到到该分支 ) (可使用 git status 查看目前处于哪一个 ...
- 《Linux内核原理与分析》第二周作业
反汇编一个简单的C程序 1.实验要求 使用: gcc –S –o test.s test.c -m32 命令编译成汇编代码,对汇编代码进行分析总结.其中test.c的具体内容如下: int g(int ...
- js生成的验证码
例1 <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title&g ...
- torchvision里densenet代码分析
#densenet原文地址 https://arxiv.org/abs/1608.06993 #densenet介绍 https://blog.csdn.net/zchang81/article/de ...
- Python生成器(generator)和迭代器(Iterator)
列表生成式 a = [i+1 for i in range(10)] print(a) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 这就是列表生成式 生成器(generator) ...
- 数字证书的理解以及自建CA机构颁发证书
一.理解什么是数字证书 http://www.cnblogs.com/JeffreySun/archive/2010/06/24/1627247.html 理解数字证书等概念,无数次想好好看 ...
- 如何用原生js开发一个Chrome扩展程序
原文地址:How to Build a Simple Chrome Extension in Vanilla JavaScript 开发一个Chrome扩展程序非常简单,只需要使用原生的js就可以完成 ...
- Logistic Loss的简单讨论
首先应该知道Logistic Loss和Crossing Entropy Loss本质上是一回事. 所以所谓的SoftMaxLoss就是一般二分类LogisitcLoss的推广.之所以在网络中采取这种 ...
- shell 生成MAC地址
# cat /dev/urandom |od -x |awk '{print $2,$3,$4}' |head -n 1 |sed -e 's/[[:space:]]//g' -e 's/\(..\) ...