leetcode -- House Robber II -- 重点dp

https://leetcode.com/problems/house-robber-ii/

注意思路:对于第一个house, 判断其“rob” or “not rob”. if rob, 那么结果就是nums[0] + rob_linear(nums[2:i-1]); if not rob, 结果就是 rob_linear(nums[1:i])

参考:
http://bookshadow.com/weblog/2015/05/20/leetcode-house-robber-ii/ 还有更好的方法

my code:

class Solution(object):

    def rob_linear(self, nums):
        """ :type nums: List[int] :rtype: int """
        if len(nums) == 0:
            return 0
        d = [0] * (len(nums) + 1)
        d[1] = nums[0]
        for i in xrange(2, len(nums) + 1):
            d[i] = max(d[i - 2] + nums[i - 1], d[i - 1])
        return d[len(nums)]

    def rob(self, nums):
        """ :type nums: List[int] :rtype: int """
        n = len(nums)
        if n == 0: return 0
        #写下初始情况各个值对应的结果,便于分析理解
        #if n == 1: d[1] = nums[0]
        #if n == 2: d[2] = max(nums)
        #if n == 3: d[3] = max(nums[0], self.rob_linear(nums[1:]))

        return max(nums[0] + self.rob_linear(nums[2:n-1]) , self.rob_linear(nums[1:]))

你可能感兴趣的:(LeetCode)