198. House Robber

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

题意:你是一个专业的强盗,计划沿着一条街盗窃。 每个房子都有一定数量的钱,唯一限制你盗窃的是相邻的房屋有安全系统连接,如果两个相邻的房屋在同一天晚上被打破,它会自动联系警察。
给出一个代表每个房子中金钱数量的非负整数的列表,确定你今天晚上可以盗窃的最大金额,而不用警报。

动态规划解决此题,下面是思路:

我们定义一个dp[]数组用来记录盗窃所得到的最大金钱数量。其中dp[i]表示盗窃前i+1所房子获得的最大金钱数量。

递推规律为:

1.如果dp[i-1]和dp[i-2]相等,那么我们可以知道第i所房子并没有被我们盗窃,从而dp[i] = dp[i-1]+第i+1所房子中的金钱(如果第i+1所房子中的金钱为0,我们将不会盗窃,此时递推公式不变

2.如果dp[i-1]和dp[i-2]不相等,那么我们可以知道第i所房子已被我们盗窃,从而dp[i]=   (dp[i-1]) 和 (dp[i-1]+第i+1所房子中的金钱) 中的较大值。

最后,dp[]数组的末尾值即为我们要求的结果。

下面贴代码:

public class Solution {
    public int rob(int[] nums) {
        if(nums.length==0) return 0;
        if(nums.length==1) return nums[0];
        if(nums.length==2) return Math.max(nums[0],nums[1]);
        int[] dp = new int[nums.length];   //定义dp数组
        dp[0] = nums[0];    //初始化dp[0] dp[1]
        dp[1] = Math.max(nums[0],nums[1]);
        for(int i=2;i<nums.length;i++){    循环计算dp数组的值
            if(dp[i-1] != dp[i-2]) dp[i] = Math.max(dp[i-1],dp[i-2]+nums[i]);
            else dp[i] = nums[i] + dp[i-1];
        }
        return dp[nums.length-1];
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值