leetcode_198. House Robber 抢劫不相邻的房子,使得抢到的金钱数目最大, 动态规划

来源:互联网 发布:动态规划的最优化原理 编辑:程序博客网 时间:2024/03/29 03:28

题目:

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 0