Python实现"打家劫舍"的一种方法

你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警

给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额

Example 1:

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
             Total amount you can rob = 1 + 3 = 4.

Example 2:

Input: [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
             Total amount you can rob = 2 + 9 + 1 = 12.

1:动态规划,迭代的方法(参考:https://www.cnblogs.com/grandyang/p/4383632.html

我们先拿一个简单的例子来分析一下,比如说nums为{3, 2, 1, 5},那么我们来看我们的dp数组应该是什么样的,首先dp[0]=3没啥疑问,再看dp[1]是多少呢,由于3比2大,所以我们抢第一个房子的3,当前房子的2不抢,所以dp[1]=3,那么再来看dp[2],由于不能抢相邻的,所以我们可以用再前面的一个的dp值加上当前的房间值,和当前房间的前面一个dp值比较,取较大值当做当前dp值,所以我们可以得到递推公式dp[i] = max(num[i] + dp[i - 2], dp[i - 1])

def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        if len(nums)==1:
            return nums[0]
        sumList = [nums[0]]      #存放盗窃的每一个房间的最大收益
        sumList.append(max(nums[0], nums[1]))
        for i in range(2,len(nums)):
            sumList.append(max(sumList[i-2]+nums[i], sumList[i-1]))
        return sumList[-1]

动态规划另一种写法:

def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        if len(nums)==1:
            return nums[0]
        first = nums[0]
        second = max(nums[0], nums[1])
        for i in range(2,len(nums)):
            second, first = max(first+nums[i], second), second   #该写法和注释的效果一样
            # temp = second
            # second = max(first+nums[i], second)
            # first = temp
        return second

算法题来自:https://leetcode-cn.com/problems/house-robber/description/

猜你喜欢

转载自blog.csdn.net/qiubingcsdn/article/details/82764616