[LeetCode]198. House Robber

198. House Robber

题意:盗贼可以到任意的房间偷东西,但是偷相邻的房间则会报警,求在不报警的情况下,偷到的最大数目的钱。

思路

这种求最大数目的题目,首先想到的就是动态规划,可以使用两个数组,分别纪录对当前房间进行偷和不偷操作后的最大数目。如果是偷当前房间,那么则不会去偷前一间房间,如果是不偷当前的房间,那么满足不偷相邻房间的条件,于是需要取不偷前一间房间和偷前一间房间的最大值。最后求偷和不偷的最大值。

状态转移方程为:

notrob_dp[i] = max(notrob_dp[i-1], rob_dp[i-1]) (if not rob current home)
rob_dp[i] = notrob_dp[i-1] + nums[i] (if rob current home)
class Solution(object):
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        elif len(nums) == 1:
            return nums[0]
        elif len(nums) == 2:
            return max(nums)
        l = len(nums)
        rob_dp = [nums[0]]  + [0] * (l-1)
        notrob_dp = [0] * l
        for i in range(1, l):
            # 偷当前房屋
            cur_rob = notrob_dp[i-1] + nums[i]
            # 不偷当前房屋
            notrob_dp[i] = max(notrob_dp[i-1], rob_dp[i-1])
            # 更新
            rob_dp[i] = cur_rob
        return max(rob_dp[l-1], notrob_dp[l-1])

我们发现其实只需要维护一个变量就可以了,而不必使用数组,如下:

class Solution(object):
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        rob, not_rob = 0, 0
        for i in range(len(nums)):
            cur_rob = not_rob + nums[i]
            not_rob = max(not_rob, rob)
            rob = cur_rob
        return max(rob, not_rob)
posted @ 2017-08-29 12:39  banananana  阅读(120)  评论(0)    收藏  举报