LeetCode-337.House Robber III
来源:互联网 发布:软件部门管理制度 编辑:程序博客网 时间:2024/05/23 00:06
https://leetcode.com/problems/house-robber-iii/
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night.
Determine the maximum amount of money the thief can rob tonight without alerting the police.
Example 1:
3 / \ 2 3 \ \ 3 1Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
3 / \ 4 5 / \ \ 1 3 1Maximum amount of money the thief can rob = 4 + 5 = 9.
感觉很简单的一道题,就是没解出来...
/** * 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[] A = dfs(root); return Math.Max(A[0], A[1]); } private int[] dfs(TreeNode node) { if (node == null) return new int[2]; int[] left = dfs(node.left); int[] right = dfs(node.right); int[] A = new int[2]; A[0] = left[1] + node.val + right[1]; A[1] = Math.Max(left[0], left[1]) + Math.Max(right[0], right[1]); return A; }}
解析
A[0]是包括根节点的情况,A[1]是不包含根节点的情况
参考 https://segmentfault.com/a/1190000005029568
0 0
- [leetcode] 337. House Robber III
- LeetCode#337. House Robber III
- LeetCode *** 337. House Robber III
- [leetcode]337. House Robber III
- LeetCode-337. House Robber III
- [leetcode]337. House Robber III
- LeetCode-337.House Robber III
- LeetCode 337. House Robber III
- Leetcode 337. House Robber III
- leetcode 337. House Robber III
- LeetCode - 337. House Robber III
- 【LeetCode】337. House Robber III
- 【leetcode】337. House Robber III
- [leetcode] 337. House Robber III
- LeetCode 337. House Robber III
- 【LeetCode】337. House Robber III
- LeetCode 337. House Robber III
- LeetCode 337. House Robber III
- synchronized
- 线程中CreateEvent和SetEvent及WaitForSingleObject的用法
- android studio does not point to jvm installation
- 使用svn的合理姿势
- 斐波那契数列11
- LeetCode-337.House Robber III
- 13.6 线程的生命周期状态,线程常用的方法
- <1> perl概述
- KMP字符串匹配
- 基于Python的接口测试框架
- Spark学习15之用Maven编译时报 java.lang.OutOfMemoryError: PermGen space异常
- js中undefined,null,NaN的区别
- 有向路径检查
- windows下protobuf jar包的编译