【LeetCode】198. 入室偷窃

问题描述

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.

你是一个专业的强盗,计划去抢劫街道上的房子。每家都有一定数量的钱被藏起来,阻止你抢劫他们的唯一限制是相邻的房子都有安全系统连接,如果两个相邻的房子在同一天晚上被闯入,它会自动联系警察。
给出一个非负整数的清单,代表每家的钱数,确定你今晚不报警就能抢劫的最大钱数。


输入: [1,2,3,1]
输出: 4
期待结果: 偷窃 房子1 (money = 1) 然后偷窃 房子3 (money = 3).
         总收益 = 1 + 3 = 4.


输入: [2,7,9,3,1]
输出: 12
期待结果: 偷窃 房子1 (money = 2), 偷窃 房子3 (money = 9) 然后偷窃 房子5 (money = 1).
         总收益 = 2 + 9 + 1 = 12.

 

Python 实现

这个问题要求不能取到相邻位置的两个数,为了取得最大效益,两个取值之间的索引间距必然不能大于2(要么间隔1,要么间隔2)。因此,这个问题可以使用动态规划的方法来解决,除去特殊情况外,我们将数组里的数 4 个为一组来进行分析:

索引 index i - 3 i - 2 i -1 i
当前最大收益 maxVal maxV1 maxV2 (暂记为 maxV3) maxV1 + nums[ i ]
maxV1 + nums[ i-1 ] maxV2 +nums[ i ]
maxV2 maxV3

从表中可以看出,我们遍历到索引 i 之前,在前面三个位置能得到的当前最大收益。对于位置 i - 1,如果在 i - 2 没有下手行窃,那么在 i - 1 一定要下手,才能得到最大收益为在 i - 3 的收益加上在该位置的收益;如果在 i - 2 下手了,那么在 i - 1 便不能下手,则当前最大收益为 maxV2,即收益不变,跟在 i - 2 时相同。

对于位置 i,收益 maxV1 + nums[ i ] 代表在 i - 2 和 i - 1 两个位置都没有下手;收益 maxV2 +nums[ i ] 代表在 i - 2 下手,在 i - 1 没有下手;收益 maxV3 则代表在 i - 1 已经下手,因此在 i 不动手。

代码的表述则更加直观,具体代码实现如下:

class Solution(object):
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        
        size = len(nums)
        if size == 0:
            return 0
        elif size == 1:
            return nums[0]
        elif size == 2:
            return max(nums[0], nums[1])
        
        # Dynamic programming (every 4 numbers a group)
        maxV1 = nums[0]
        maxV2 = nums[1]
        
        maxV3 = max(nums[1], nums[2] + maxV1)
        
        for i in range(3, size):
            maxVal = max(maxV3, maxV1 + nums[i], maxV2 + nums[i])
            maxV1, maxV2, maxV3 = maxV2, maxV3, maxVal
            
        return max(maxV2, maxV3)

链接:https://leetcode.com/problems/house-robber/

发布了45 篇原创文章 · 获赞 29 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/sinat_36645384/article/details/103683562
今日推荐