We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 135741a commit cbfb8c6Copy full SHA for cbfb8c6
solution/0100-0199/0198.House Robber/Solution.java
@@ -1,11 +1,20 @@
1
class Solution {
2
+ private Integer[] f;
3
+ private int[] nums;
4
+
5
public int rob(int[] nums) {
- int n = nums.length;
- int[] f = new int[n + 1];
- 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]);
+ this.nums = nums;
+ 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));
17
}
- return f[n];
18
+ return f[i];
19
-}
20
+}
0 commit comments