kniost

谁怕,一蓑烟雨任平生

0%

LeetCode 198/213/337 House Robber 系列问题


题目原文

337. House Robber III

Difficulty: Medium

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]

1
2
3
4
5
  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]

1
2
3
4
5
    3
/ \
4 5
/ \ \
1 3 1

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

解法

动态规划

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* 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) {
int[] result = helper(root);

return Math.max(result[0], result[1]);
}

// 数组第1位表示使用root的值,第二位表示不用
public int[] helper(TreeNode root) {
if (root == null) {
return new int[] {0, 0};
}
int[] left = helper(root.left);
int[] right = helper(root.right);
int[] result = new int[2];
result[0] = root.val + left[1] + right[1];
result[1] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
return result;
}
}

记忆化搜索

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
Map<TreeNode, Integer> trueMap = new HashMap<>();
Map<TreeNode, Integer> falseMap = new HashMap<>();
public int rob(TreeNode root) {
if (root == null) {
return 0;
}
return Math.max(helper(root, true), helper(root, false));
}

public int helper(TreeNode root, boolean grab) {
if (root == null) {
return 0;
}
if (grab) {
if (trueMap.containsKey(root)) {
return trueMap.get(root);
} else {
int val = root.val + helper(root.left, false) + helper(root.right, false);
trueMap.put(root, val);
return val;
}
} else {
if (falseMap.containsKey(root)) {
return falseMap.get(root);
} else {
int val = Math.max(helper(root.left, true), helper(root.left, false)) +
Math.max(helper(root.right, true), helper(root.right, false));
falseMap.put(root, val);
return val;
}
}
}
}