力扣-213.打家劫舍 II

力扣-213.打家劫舍 II_第1张图片

力扣-213.打家劫舍 II_第2张图片

在前一题力扣-198.打家劫舍_Node_Su的博客-CSDN博客的基础上,设置房屋围成一圈,即三个的时候,1 3 不可同时取

围成一圈则考虑

打劫[0,n-1]的结果和[1,n]的结果哪个最优,即为最终最优解

class Solution(object):
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        n = len(nums)
        if n == 1:
            return nums[0]
        return max(self.rob_1(nums[0:n - 1]), self.rob_1(nums[1:n]))

    def rob_1(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        n = len(nums)

        dp = [0] * n  # 初始钱包为0
        dp[0] = nums[0]
        if n == 1:
            return nums[0]
        if n == 2:
            dp[1] = max(nums[0], nums[1])
            return dp[1]
        if n >= 3:
            dp[1] = max(nums[0], nums[1])
            dp[2] = max(nums[0] + nums[2], nums[1])
            for i in range(3, n):
                dp[i] = max(dp[i - 2] + nums[i], dp[i - 3] + nums[i])
            res = -1
            for i in range(n):
                res = max(dp[i], res)
            return res


if __name__ == '__main__':
    nums = [1, 2, 1, 1]
    Sol = Solution()
    res = Solution.rob(Sol, nums)
    print(res)

你可能感兴趣的:(学习笔记,python)