LeetCode 337. House Robber III
原题链接在这里: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 1
Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
3 / \ 4 5 / \ \ 1 3 1
Maximum amount of money the thief can rob = 4 + 5 = 9.
题解:
List some examples and find out this has to be done with DFS.
One or null node is easy to think, thus use DFS bottom-up, devide and conquer.
Then it must return value on dfs. Each dfs needs current node and return [robRoot, notRobRoot], which denotes rob or skip current node.
robRoot = notRobLeft + notRobRight + root.val
notRobRoot = Math.max(robLeft, notRobLeft) + Math.max(robRight, notRobRight).
Note: when not robbint root, for left and right children. It could choose to rob child node or not.
Time Complexity: O(n).
Space: O(logn). 用了logn层stack.
AC Java:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public int rob(TreeNode root) { 12 int [] res = dfs(root); 13 return Math.max(res[0], res[1]); 14 } 15 private int [] dfs(TreeNode root){ 16 int [] dp = new int[2]; 17 if(root == null){ 18 return dp; 19 } 20 int [] left = dfs(root.left); 21 int [] right = dfs(root.right); 22 //dp[0]表示偷root的, 那么左右都不能偷, 所以用left[1], right[1]. 23 dp[0] = left[1] + right[1] + root.val; 24 //dp[1]表示不偷root的, 那么左右偷不偷都可以, 取最大值 25 dp[1] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]); 26 return dp; 27 } 28 }