本文共 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/