337. House Robber III二叉樹上的搶劫題

[抄題]:node

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:數據結構

Input: [3,2,3,null,3,null,1]

     3
    / \
   2   3
    \   \ 
     3 1 
Output: 7 
Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.

Example 2:ide

Input: [3,4,5,1,3,null,1]

     3
    / \
   4   5
  / \   \ 
 1   3   1

Output: 9
Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.

 [暴力解法]:優化

時間分析:this

空間分析:spa

 [優化後]:debug

時間分析:code

空間分析:

[奇葩輸出條件]:

[奇葩corner case]:

[思惟問題]:

知道是dc,不知道具體怎麼寫。用dc能夠新生成數組,不須要別的參數。由於數組裏面的元素只有2個,指定一下就好了。

[英文數據結構或算法,爲何不用別的數據結構或算法]:

數組:由於只有偷與否2種狀態,left right res都須要在其中比較,因此開空間爲2的數組便可

[一句話思路]:

[輸入量]:空: 正常狀況:特大:特小:程序裏處理到的特殊狀況:異常狀況(不合法不合理的輸入):

[畫圖]:

[一刷]:

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分鐘肉眼debug的結果]:

[總結]:

用dc能夠新生成數組,不須要別的參數。由於數組裏面的元素只有2個,指定一下就好了。

[複雜度]:Time complexity: O(n) Space complexity: O(n)

[算法思想:迭代/遞歸/分治/貪心]:

[關鍵模板化代碼]:

[其餘解法]:

[Follow Up]:

[LC給出的題目變變變]:

 [代碼風格] :

 [是否頭一次寫此類driver funcion的代碼] :

 [潛臺詞] :

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int rob(TreeNode root) {
        //corner case
        if (root == null) return 0; 
        
        //call the robHelper
        int[] result = robHelper(root);
        
        //compare and return
        return Math.max(result[0], result[1]);
    }
    
    public int[] robHelper(TreeNode root) {
        //corner case
        if (root == null) return new int[2];
        int[] result = new int[2];
        
        //initialization : 2 int[] left and right
        int[] left = robHelper(root.left);
        int[] right = robHelper(root.right);
        
        //define the numbers
        //choose root
        result[1] = left[0] + root.val + right[0];  
        //not choose
        result[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
        
        //return
        return result;
    }
}
View Code
相關文章
相關標籤/搜索