Skip to content

Commit 2ed7661

Browse files
refactor 198
1 parent 34ee3d3 commit 2ed7661

File tree

2 files changed

+57
-3
lines changed

2 files changed

+57
-3
lines changed

src/main/java/com/fishercoder/solutions/_198.java

+27-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package com.fishercoder.solutions;
22

3+
import java.util.Arrays;
4+
35
public class _198 {
46

57
public static class Solution1 {
@@ -10,9 +12,6 @@ public int rob(int[] nums) {
1012
if (nums.length == 1) {
1113
return nums[0];
1214
}
13-
if (nums.length == 2) {
14-
return Math.max(nums[0], nums[1]);
15-
}
1615
int[] dp = new int[nums.length];
1716
dp[0] = nums[0];
1817
dp[1] = Math.max(nums[0], nums[1]);
@@ -22,4 +21,29 @@ public int rob(int[] nums) {
2221
return dp[nums.length - 1];
2322
}
2423
}
24+
25+
public static class Solution2 {
26+
/**
27+
* recursion + memoization, basically the same as the above solution1
28+
* credit: https://leetcode.com/problems/house-robber/solution/
29+
*/
30+
int[] memo;
31+
32+
public int rob(int[] nums) {
33+
memo = new int[nums.length];
34+
Arrays.fill(memo, -1);
35+
return robFrom(0, nums);
36+
}
37+
38+
private int robFrom(int start, int[] nums) {
39+
if (start >= nums.length) {
40+
return 0;
41+
}
42+
if (this.memo[start] != -1) {
43+
return this.memo[start];
44+
}
45+
this.memo[start] = Math.max(robFrom(start + 1, nums), robFrom(start + 2, nums) + nums[start]);
46+
return this.memo[start];
47+
}
48+
}
2549
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.fishercoder;
2+
3+
import com.fishercoder.solutions._198;
4+
import org.junit.BeforeClass;
5+
import org.junit.Test;
6+
7+
import static org.junit.Assert.assertEquals;
8+
9+
public class _198Test {
10+
private static _198.Solution1 solution1;
11+
private static _198.Solution2 solution2;
12+
13+
@BeforeClass
14+
public static void setup() {
15+
solution1 = new _198.Solution1();
16+
solution2 = new _198.Solution2();
17+
}
18+
19+
@Test
20+
public void test1() {
21+
assertEquals(4, solution1.rob(new int[]{1, 2, 3, 1}));
22+
assertEquals(4, solution2.rob(new int[]{1, 2, 3, 1}));
23+
}
24+
25+
@Test
26+
public void test2() {
27+
assertEquals(4, solution1.rob(new int[]{2, 1, 1, 2}));
28+
}
29+
30+
}

0 commit comments

Comments
 (0)