leetcode_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.


题意:

假设你是一个专业强盗,计划一天晚上去一条街上的房子里偷东西,如果同一天晚上偷两座相邻的房子,则会触发报警系统(即不能偷相邻的房子),问已知每座房子里已有金钱数目情况下,如果偷才能使偷到的金钱数量最大。

输入:一个数组,数组里的第i个数据表示第i座房子里的金钱数目。

输出:能偷到的最大金钱数目


代码:

class Solution(object):
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        
        hou_num = len(nums)
        
        if hou_num == 0 :
            return 0
        
        result = [0]*hou_num
        if hou_num == 1 :
            result[0] = nums[0]
        else :
            if hou_num >= 2 :
                result[0] = nums[0]
                result[1] = max(nums[0],nums[1])
                for i in range(2,hou_num) :
                    result[i] = max(result[i-2]+nums[i], result[i-1])
        return result[-1]


笔记:

思路:构造一个数组result[],用于存储第i座房子时,能偷到的最大金钱数目

当输入nums为空时,表示没有房子可偷,直接返回0

当输入len(nums)为1时,result直接等于nums,即第一座房子的金钱即为对打金钱数

当输入len(nums)为2时,result[0] = nums[0]  , result[1] = max(nums[0],nums[1]) ,返回result[-1] ,即取第一座和第二座房子金钱的最大值

当输入len(nums)大于2时,利用递推式 result[i] = max(result[i-2]+nums[i], result[i-1])  来计算result。因为第i座房子只有两种选择:偷与不偷,当选择偷时,当前得到的金钱数为result[i-2]+nums[i],当不偷时,当前得到的金钱数为result[i-1],取两者之间的最大值,即为到第i座房子为止,偷到的金钱的最大数目。  最后返回result[-1] 。


即状态转移方程为:

dp[0] = num[0] (当i=0时)
dp[1] = max(num[0], num[1]) (当i=1时)
dp[i] = max(num[i] + dp[i - 2], dp[i - 1])   (当i !=0 and i != 1时)

参考:

https://yq.aliyun.com/articles/3521





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值