版权声明:版权所有,转载请注明原网址链接。 https://blog.csdn.net/qq_41231926/article/details/81735003
原题链接:https://leetcode-cn.com/problems/house-robber-ii/description/
题目描述:
知识点:动态规划
基本思路:
第一个房屋和最后一个房屋是紧挨着的,说明第一个房屋和最后一个房屋不能同时盗取。我们可以考虑两种情况:
(1)考虑偷取[0, n - 2]的房屋。
(2)考虑偷取[1, n - 1]的房屋。
取上述两种情况的大者即为答案。而对于上述两种情况,其实和LeetCode198——打家劫舍是一模一样的(关于LeetCode198的分析请见我的另一篇博文:https://blog.csdn.net/qq_41231926/article/details/81697604)。
JAVA代码:
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);
}
复杂度分析:
本题只不过相当于做了两次LeetCode198——打家劫舍的过程,因此时间复杂度和空间复杂度均与LeetCode198——打家劫舍相同。
时间复杂度:O(n ^ 2)
空间复杂度:O(n)