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

解题思路:

此题的意思是,给定一个非负整数列表,从中选取元素,使得元素两两不相邻,找到满足条件的这些元素的最大和。

假设列表长度为 n,先观察规律:

当 n = 0 时,列表为空,返回 0
当 n = 1 时,列表只有一个元素,返回 nums[0]
当 n = 2 时,列表有两个元素,返回 max(nums[0], num[1])
当 n = 3 时,列表返回的下标组合可能为 [0,2] 和 [1]
当 n = 4 时,列表返回的下标组合可能为 [0,2] 、[1,3] 和 [0,3]
当 n = 5 时,列表返回的下标组合可能为 [0,2,4] 、[1,3] 、[0,3] 和 [1,4]
当 n = 6 时,列表返回的下标组合可能为 [0,2,4] 、 [1,3,5]、[0,3,5]、[1,4] 和 [0,2,5]
.....

以 n = 6 为例,[0,2,4] 和 [1,4] 均可以由 n = 5 时得到; [1,3,5]、[0,3,5] 和 [0,2,5] 可以由 n = 4 的每个元素加上 [5] 得到。

由此可以得到递归规律:

设 k 为列表最大下标,则有:
f(0) = nums[0]
f(1) = max(num[0], num[1])
f(k) = max(f(k-2) + nums[k], f(k-1))

因此,此题可以使用递归求解。时间复杂度 O(n),空间复杂度 O(1)。

Python实现:
class Solution(object):
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        high = len(nums) - 1
        if high == -1:
            return 0
        elif high == 0:
            return nums[0]
        elif high == 1:
            return max(nums[0], nums[1])
        else:
            return max(self.rob(nums[:high-1]) + nums[high], self.rob(nums[:high]))

这种方法得到的答案是正确的,但是在提交的时候会超时。因此,需要改写为非递归的方法,如下:

class Solution(object):
    def rob2(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # pre2 相当于 f(k-2), pre1 相当于 f(k-1), now 相当于 f(k)
        pre2 = pre1 = now = 0  
        for num in nums:
            pre2 = pre1
            pre1 = now
            now = max(pre2 + num, pre1)
        return now

a = [6,3,10,8,2,10,3,5,10,5,3]  
b = Solution()
print(b.rob2(a))  # 39  # 下标 [0, 2, 5, 8, 10] = 6 + 10 + 10 + 10 + 3 = 39

这种将递归方法改写为非递归方法与斐波那契数列改写方法类似,可以参考题目 Q70 Climbing Stairs

观察上述非递归方法,可以更近一步简化,即 pre2 = pre1; pre1 = now 可以合并为一句 pre2 = now, 这时 now = max(pre2 + num, pre1) 变为 now = max(pre2 + num, now):

class Solution(object):
    def rob3(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        last = now = 0 
        for num in nums:
            last, now = now, max(last + num, now)
        return now

a = [6,3,10,8,2,10,3,5,10,5,3]  
b = Solution()
print(b.rob3(a))  # 39  # 下标 [0, 2, 5, 8, 10] = 6 + 10 + 10 + 10 + 3 = 39
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容