-
Notifications
You must be signed in to change notification settings - Fork 458
/
Copy pathSolution1.java
40 lines (31 loc) · 1017 Bytes
/
Solution1.java
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
import java.util.Arrays;
/// 198. House Robber
/// https://leetcode.com/problems/house-robber/description/
/// 记忆化搜索
/// 时间复杂度: O(n^2)
/// 空间复杂度: O(n)
public class Solution1 {
// memo[i] 表示考虑抢劫 nums[i...n) 所能获得的最大收益
private int[] memo;
public int rob(int[] nums) {
memo = new int[nums.length];
Arrays.fill(memo, -1);
return tryRob(nums, 0);
}
// 考虑抢劫nums[index...nums.size())这个范围的所有房子
private int tryRob(int[] nums, int index){
if(index >= nums.length)
return 0;
if(memo[index] != -1)
return memo[index];
int res = 0;
for(int i = index ; i < nums.length ; i ++)
res = Math.max(res, nums[i] + tryRob(nums, i + 2));
memo[index] = res;
return res;
}
public static void main(String[] args) {
int nums[] = {2, 1};
System.out.println((new Solution1()).rob(nums));
}
}