我的LeetCode代码仓:https://github.com/617076674/LeetCode
原题链接:https://leetcode-cn.com/problems/house-robber-ii/description/
题目描述:
知识点:动态规划
思路:两次LeetCode198——打家劫舍
第一个房屋和最后一个房屋是紧挨着的,说明第一个房屋和最后一个房屋不能同时盗取。我们可以考虑两种情况:
(1)考虑偷取[0, n - 2]的房屋。
(2)考虑偷取[1, n - 1]的房屋。
取上述两种情况的大者即为答案。而对于上述两种情况,和LeetCode198——打家劫舍是一模一样的。
时间复杂度是O(n ^ 2)。空间复杂度是O(n)。
JAVA代码:
public class Solution {
public int rob(int[] nums) {
int n = nums.length;
if(n == 0) {
return 0;
}
if(n == 1) {
return nums[0];
}
//sum[i]:考虑偷取[0, i]范围内的房子
//1.先考虑偷取[0, n - 2]的房子
int[] sum = new int[n - 1];
sum[0] = nums[0];
for (int i = 1; i < n - 1; i++) {
sum[i] = 0;
for (int j = 0; j <= i; j++) {
if(j >= 2) {
sum[i] = Math.max(sum[i], sum[j - 2] + nums[j]);
}else {
sum[i] = Math.max(sum[i], nums[j]);
}
}
}
int result1 = sum[n - 2];
//2.再考虑偷取[1, n - 1]的房子
int[] sum2 = new int[n];
sum2[1] = nums[1];
for (int i = 2; i < n; i++) {
sum2[i] = 0;
for (int j = 1; j <= i; j++) {
if(j >= 3) {
sum2[i] = Math.max(sum2[i], sum2[j - 2] + nums[j]);
}else {
sum2[i] = Math.max(sum2[i], nums[j]);
}
}
}
int result2 = sum2[n - 1];
return Math.max(result1, result2);
}
}
LeetCode解题报告: