Skip to content

Commit cbfb8c6

Browse files
authored
Update Solution.java
1 parent 135741a commit cbfb8c6

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed
Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,20 @@
11
class Solution {
2+
private Integer[] f;
3+
private int[] nums;
4+
25
public int rob(int[] nums) {
3-
int n = nums.length;
4-
int[] f = new int[n + 1];
5-
f[1] = nums[0];
6-
for (int i = 2; i <= n; ++i) {
7-
f[i] = Math.max(f[i - 1], f[i - 2] + nums[i - 1]);
6+
this.nums = nums;
7+
f = new Integer[nums.length];
8+
return dfs(0);
9+
}
10+
11+
private int dfs(int i) {
12+
if (i >= nums.length) {
13+
return 0;
14+
}
15+
if (f[i] == null) {
16+
f[i] = Math.max(nums[i] + dfs(i + 2), dfs(i + 1));
817
}
9-
return f[n];
18+
return f[i];
1019
}
11-
}
20+
}

0 commit comments

Comments
 (0)