leetcode-easy-dynamic-198 House Robber-NO

mycode

思路:

a:1 2 3 4 5 6 7 8 9 

f(9) =max( f(7) + a9 ,f(8)) 前一步、前两步

至于前三步 f(9) = f(6)+ a9,但其实f(7)在求值的时候按照上面的公式一定是比f(7)大于等于的,所以f(6)+a9总是小于等于上面的递推式的

至于前四步更不用考虑了,因为前两步已经考虑了前四步

time limited

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)
        return max(self.rob(nums[:-2])+nums[-1],self.rob(nums[:-1]))

思路上的难点:

a :1 2 3 4 5 6 7 8 

比如a4的时候,有以下选择:f(2) + a4  ,f(3) ,至于f(1)+a4不需要再去考虑,因为f(2)一定是大于等于f(1)的

参考

1、上面是递归求解,然而复杂度太高无法AC。所以应该记录已经计算过的结果,于是这变成一个动态规划问题

class Solution(object):
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) == 0:
            return 0
        elif len(nums) < 2:
            return max(nums[0], nums[-1])
        money = [0]*len(nums)
        money[0], money[1] = nums[0], max(nums[0], nums[1])
        for i in xrange(2, len(nums)):
            money[i] = max(nums[i] + money[i-2], money[i-1])
        return money[len(nums)-1]

2、

上面的代码使用的空间是冗余的,因为每次循环只会用到前两个数据。所以代码可以降低空间复杂度到O(1)。

class Solution(object):
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        now = last = 0
        for i in nums:
            last, now = now, max(i+last, now)
        return now
原文地址:https://www.cnblogs.com/rosyYY/p/11003499.html