Skip to content

Commit 0757482

Browse files
committed
House Robber(小偷问题)
1 parent 2f1573b commit 0757482

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

LeetCode/HouseRobber.java

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,21 @@
1515
* 对于当前变量,若cur+pre>res,则更新pre和res;否则,只更新pre=res
1616
*/
1717
public class HouseRobber {
18+
19+
//优化代码的DP
20+
public int rob(int[] nums) {
21+
int pre = 0;
22+
int res = 0;
23+
for (int n : nums) {
24+
int temp = res;
25+
res = Math.max(res, pre);
26+
pre = n + temp;
27+
}
28+
return Math.max(pre, res);
29+
}
30+
31+
//原DP方法
32+
/*
1833
public int rob(int[] nums) {
1934
int pre = 0;
2035
if (nums == null || nums.length == 0) {
@@ -23,8 +38,8 @@ public int rob(int[] nums) {
2338
if (nums.length == 1) return nums[0];
2439
int res = nums[0];
2540
for (int i = 1; i < nums.length; i++) {
26-
int cur = pre + nums[i];
27-
if (cur > res) {
41+
if (nums[i] + pre > res) {
42+
int cur = pre + nums[i];
2843
pre = res;
2944
res = cur;
3045
} else {
@@ -33,6 +48,7 @@ public int rob(int[] nums) {
3348
}
3449
return res;
3550
}
51+
*/
3652

3753
public static void main(String[] args) {
3854
int[] nums = {1, 4, 5, 3, 8, 2, 3, 4};

0 commit comments

Comments
 (0)