力扣-198.打家劫舍

力扣-198.打家劫舍_第1张图片

解法一:

dp[i]表示打劫到当前第 i 家的最大金额

首先,前3家特殊处理

然后,是否打劫当前家应考虑打劫 i-2 家和 i-3 是否能达到最大收益,因为不能打劫邻居 i-1

class Solution(object):
    def rob(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)

解法二: 

考虑当前家偷不偷

如果偷,则是 i-2 家的金额+当前家的金额

如果不偷,则是偷前 i-1 家的金额

比较两种情况的大小

class Solution(object):
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        n = len(nums)

        dp = [0] * n
        dp[0] = nums[0]
        if n == 1:
            return nums[0]

        dp[1] = max(nums[1], nums[0])
        for i in range(2, len(nums)):
            dp[i] = max(dp[i - 1], dp[i - 2] + nums[i])  # 不偷,偷
        return dp[len(dp) - 1]


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

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