1. 程式人生 > 其它 >【LeetCode】337. House Robber III 打家劫舍 III(Medium)(JAVA)

【LeetCode】337. House Robber III 打家劫舍 III(Medium)(JAVA)

技術標籤:Leetcodejavaleetcode演算法面試資料結構

【LeetCode】337. House Robber III 打家劫舍 III(Medium)(JAVA)

題目地址: 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:

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:

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.

題目大意

在上次打劫完一條街道之後和一圈房屋後,小偷又發現了一個新的可行竊的地區。這個地區只有一個入口,我們稱之為“根”。 除了“根”之外,每棟房子有且只有一個“父“房子與之相連。一番偵察之後,聰明的小偷意識到“這個地方的所有房屋的排列類似於一棵二叉樹”。 如果兩個直接相連的房子在同一天晚上被打劫,房屋將自動報警。

計算在不觸動警報的情況下,小偷一晚能夠盜取的最高金額。

解題方法

暴力求解

  1. 直接暴力每個都判斷當前是否需要偷;如果當前偷,下一個就不能再偷,如果當前不偷,下一個就可以偷
  2. 每次都需要遍歷子樹兩次
class Solution {
    public int rob(TreeNode root) {
        return robHelp(root, true);
    }

    public int robHelp(TreeNode root, boolean canRob) {
        if (root == null) return 0;
        if (canRob) {
            return Math.max(robHelp(root.left, true) + robHelp(root.right, true), root.val + robHelp(root.left, false) + robHelp(root.right, false));
        } else {
            return robHelp(root.left, true) + robHelp(root.right, true);
        }
    }
}

執行耗時:1546 ms,擊敗了5.00% 的Java使用者
記憶體消耗:38.5 MB,擊敗了36.54% 的Java使用者

優化

  1. 暴力方法對子樹每次都遍歷了兩遍,造成越往下,遍歷的次數是指數增長的,所以想辦法能不能遍歷一次就把偷和不偷的結果都返回呢?
  2. 這樣需要返回值是一個數組(同時返回偷和不偷的結果)
  3. 如果偷的話,子樹肯定就不能偷了,就是 root.val + function(roo.left)[不偷] + …;
  4. 如果不偷,那子樹既可以偷也可以不偷,取兩個的最大值,Math.max(function(root.left)[偷], function(root.left)[不偷])
class Solution {
    public int rob(TreeNode root) {
        int[] res = robHelp(root);
        return Math.max(res[0], res[1]);
    }

    // int[0]: rob; int[1]: not rob
    public int[] robHelp(TreeNode root) {
        if (root == null) return new int[]{0, 0};
        int[] left = robHelp(root.left);
        int[] right = robHelp(root.right);
        return new int[]{left[1] + right[1] + root.val, Math.max(left[0], left[1]) + Math.max(right[0], right[1])};
    }
}

執行耗時:0 ms,擊敗了100.00% 的Java使用者
記憶體消耗:38.3 MB,擊敗了58.62% 的Java使用者

歡迎關注我的公眾號,LeetCode 每日一題更新