LeetCode.213.打家劫舍II

原题链接:https://leetcode-cn.com/problems/house-robber-ii/
根据官方给出的提示:
因为房间n和房间1是相邻的,所以不能同时抢房间1和房间n。所以问题就变成了是抢劫House[1]~House[n-1]还是抢House[2]~House[n],会获取更大的利润。因为打家劫舍问题已经被解决。

class Solution(object):
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        def maxrob(nums): # 解决打家劫舍问题
            if nums == []:
                return 0
            length = len(nums)
            memo = [0]*length
            memo[-1] = nums[-1]
            for i in range(length-2,-1,-1):
                memo[i] = max(nums[i] + (0 if i+2>=length else memo[i+2]), \
                              nums[i+1] +(0 if i+3 >= length else memo[i+3]))
            return memo[0]
        length = len(nums)
        if length == 0:
            return 0
        if length <= 2:  # 如果数组长度小于2,返回最大值
            return max(nums)
        else:
            return max(maxrob(nums[:-1]),maxrob(nums[1:]))

你可能感兴趣的:(算法)