-
Notifications
You must be signed in to change notification settings - Fork 0
/
198.java
59 lines (55 loc) · 1.47 KB
/
198.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class Solution {
public int rob(int[] nums) {
if(nums.length==1)
return nums[0];
if(nums.length==2)
return Math.max(nums[0],nums[1]);
int[] dp = new int[nums.length + 1];
dp[1] = nums[0];
dp[2] = nums[1];
for (int i = 3; i <= nums.length; i++) {
dp[i]=Math.max(dp[i-2]+nums[i-1],dp[i-3]+nums[i-1]);
}
return Math.max(dp[nums.length],dp[nums.length-1]);
}
}
// class Solution {
// private int[] nums,memo;
// public int rob(int[] nums) {
// this.nums = nums;
// int n = nums.length;
// memo = new int[n];
// Arrays.fill(memo,-1);
// return dfs(n-1);
// }
// private int dfs(int i){
// if(i<0)
// return 0;
// if(memo[i]!=-1){
// return memo[i];
// }
// int ans = Math.max(dfs(i-1),dfs(i-2)+nums[i]);
// memo[i]=ans;
// return ans;
// }
// }
// 第二次做法,统一写法
class Solution {
private int[] nums;
private int[] memo;
public int rob(int[] nums) {
this.nums = nums;
memo = new int[nums.length];
Arrays.fill(memo,-1);
return dfs(nums.length-1);
}
private int dfs(int length){
if(length<0){
return 0;
}
if(memo[length]!=-1){
return memo[length];
}
return memo[length] = Math.max(dfs(length-1) , dfs(length-2)+nums[length]);
}
}