LeetCode213——打家劫舍II

我的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解题报告:

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值