Skip to content

Commit 405504b

Browse files
committed
#198 打家劫舍-1 dp, 三个优化版本
1 parent 2102147 commit 405504b

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

main/src/dynamic_programming/LC_198_HouseRobber.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,34 @@ public int rob(int[] nums) {
2727
}
2828
return Math.max(dp[nums.length - 1][1], dp[nums.length - 1][0]);
2929
}
30+
31+
/**
32+
* 只用以为数据记录每栋房子必偷时的金币数量(必偷,但是不拿金币),取dp数组中的最大值,就是所得的金币
33+
* 5:17 PM info
34+
* Success:
35+
* Runtime:0 ms, faster than 100.00% of Java online submissions.
36+
* Memory Usage:36.6 MB, less than 5.02% of Java online submissions.
37+
*/
38+
public int rob_pretty(int[] nums) {
39+
int[] dp = new int[nums.length];
40+
dp[0] = nums[0];
41+
dp[1] = Math.max(nums[0], nums[1]);
42+
int max = Math.max(dp[0], dp[1]);
43+
for (int i = 2; i < nums.length; i++) {
44+
dp[i] = Math.max(dp[i - 1] + 0, dp[i - 2] + nums[i]);
45+
max = Math.max(max, dp[i]);
46+
}
47+
return max;
48+
}
49+
50+
public int rob_pretty_1_array(int[] nums) {
51+
int prevMax = 0;
52+
int currMax = 0;
53+
for (int i = 0; i < nums.length; i++) {
54+
int temp = currMax;
55+
currMax = Math.max(prevMax + nums[i], currMax);
56+
prevMax = temp;
57+
}
58+
return currMax;
59+
}
3060
}

main/test/dynamic_programming/LC_198_HouseRobberTest.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,16 @@ public void house_robby_test() {
1515
LC_198_HouseRobber houseRobber = new LC_198_HouseRobber();
1616
assertThat(houseRobber.rob(new int[]{1, 2, 3, 1}), is(4));
1717
}
18+
19+
@Test
20+
public void house_robby_pretty_test() {
21+
LC_198_HouseRobber houseRobber = new LC_198_HouseRobber();
22+
assertThat(houseRobber.rob_pretty(new int[]{1, 2, 3, 1}), is(4));
23+
}
24+
25+
@Test
26+
public void house_robby_pretty_1_array_test() {
27+
LC_198_HouseRobber houseRobber = new LC_198_HouseRobber();
28+
assertThat(houseRobber.rob_pretty_1_array(new int[]{1, 2, 3, 1}), is(4));
29+
}
1830
}

0 commit comments

Comments
 (0)