码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode House Robber III

时间:2016-03-27 07:13:28      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

原题链接在这里: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.

题解:

robRoot = notRobLeft + notRobRight + root.val

notRobRoot = Math.max(robLeft, notRobLeft) + Math.max(robRight, notRobRight).

树用的dfs从底往上更新.

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 }

 类似House RobberHouse Robber II.

LeetCode House Robber III

标签:

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/5324753.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!