Skip to content

Commit e3c63b6

Browse files
authored
Simplify House Robber solution
1 parent 170f0fc commit e3c63b6

File tree

1 file changed

+11
-20
lines changed

1 file changed

+11
-20
lines changed

notes/Leetcode 题解.md

Lines changed: 11 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2415,35 +2415,27 @@ public int climbStairs(int n) {
24152415
定义 dp 数组用来存储最大的抢劫量,其中 dp[i] 表示抢到第 i 个住户时的最大抢劫量。
24162416

24172417
由于不能抢劫邻近住户,因此如果抢劫了第 i 个住户那么只能抢劫 i - 2 或者 i - 3 的住户,所以
2418-
2419-
<div align="center"><img src="https://latex.codecogs.com/gif.latex?dp[i]=max(dp[i-2],dp[i-3])+nums[i]"/></div> <br>
2418+
dp[i] = max(dp[i-1], dp[i-2] + nums[i]) <br>
24202419

24212420
```java
24222421
public int rob(int[] nums) {
2423-
int n = nums.length;
2424-
if (n == 0) {
2425-
return 0;
2426-
}
2427-
if (n == 1) {
2428-
return nums[0];
2429-
}
2430-
int pre3 = 0, pre2 = 0, pre1 = 0;
2431-
for (int i = 0; i < n; i++) {
2432-
int cur = Math.max(pre2, pre3) + nums[i];
2433-
pre3 = pre2;
2422+
int pre2 = 0, pre1 = 0;
2423+
for (int i = 0; i < nums.length; i++) {
2424+
int cur = Math.max(pre2 + nums[i], pre1);
24342425
pre2 = pre1;
24352426
pre1 = cur;
24362427
}
2437-
return Math.max(pre1, pre2);
2428+
return pre1;
24382429
}
2430+
24392431
```
24402432

24412433
**强盗在环形街区抢劫**
24422434

24432435
[213. House Robber II (Medium)](https://leetcode.com/problems/house-robber-ii/description/)
24442436

24452437
```java
2446-
public int rob(int[] nums) {
2438+
public int rob(int[] nums) {
24472439
if (nums == null || nums.length == 0) {
24482440
return 0;
24492441
}
@@ -2454,15 +2446,14 @@ public int rob(int[] nums) {
24542446
return Math.max(rob(nums, 0, n - 2), rob(nums, 1, n - 1));
24552447
}
24562448

2457-
private int rob(int[] nums, int first, int last) {
2458-
int pre3 = 0, pre2 = 0, pre1 = 0;
2449+
private int rob(int[] nums, int first, int last) {
2450+
int pre2 = 0, pre1 = 0;
24592451
for (int i = first; i <= last; i++) {
2460-
int cur = Math.max(pre3, pre2) + nums[i];
2461-
pre3 = pre2;
2452+
int cur = Math.max(pre1, pre2 + nums[i]);
24622453
pre2 = pre1;
24632454
pre1 = cur;
24642455
}
2465-
return Math.max(pre2, pre1);
2456+
return pre1;
24662457
}
24672458
```
24682459

0 commit comments

Comments
 (0)