博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【Leetcode刷题篇】leetcode337 打家劫舍III
阅读量:1888 次
发布时间:2019-04-26

本文共 823 字,大约阅读时间需要 2 分钟。

在上次打劫完一条街道之后和一圈房屋后,小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为“根”。 除了“根”之外,每栋房子有且只有一个“父“房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 如果两个直接相连的房子在同一天晚上被打劫,房屋将自动报警。

计算在不触动警报的情况下,小偷一晚能够盗取的最高金额。

在这里插入图片描述

解题思路:一棵二叉树,树上的每个点都有对应的权值,每个点有两种状态(选中和不选中),问在不能同时选中有父子关系的点的情况下,能选中的点的最大权值和是多少?

在这里插入图片描述

package com.lcz.leetcode;public class Leetcode377 {
class TreeNode{
int val; TreeNode left; TreeNode right; TreeNode(int x){
val = x; } } public int rob(TreeNode root) {
int[] res = dfs(root); return Math.max(res[0], res[1]); } // 遍历 public int[] dfs(TreeNode node) {
if(node==null) {
return new int[] {
0,0}; } int[] l = dfs(node.left); int[] r = dfs(node.right); int selected = node.val + l[1] + r[1]; int notselected = Math.max(l[0],l[1]) + Math.max(r[0],r[1]); return new int[] {
selected,notselected}; }}

转载地址:http://dbwdf.baihongyu.com/

你可能感兴趣的文章
Nexus+Nginx+docker
查看>>
DTO
查看>>
DDD
查看>>
wcf messageEncoding="Mtom"
查看>>
asp.net core webapi post
查看>>
C#中使用TransactionScope类(分布式事务) 和 锁
查看>>
SecurityProtocolType
查看>>
Consul、Ocelot、Docker
查看>>
消息队列
查看>>
BPM/OA/审批流/工作流
查看>>
艾维利时间管理法
查看>>
c# – AuthenticationHeaderValue与NetworkCredential
查看>>
我的sql自定义分页
查看>>
阿里入职培训,针不搓
查看>>
我的游标分页
查看>>
js比较两个String字符串找出不同,并将不同处高亮显示
查看>>
进程以下的那些事儿
查看>>
宏内核与微内核
查看>>
python异步函数中调用同步函数
查看>>
Python异步库里面的队列
查看>>