边工作边刷题:70天一遍leetcode: day 38

House Robber I/II/III

这题代表了单向线性dp的基本pattern: build local best value at each element and track the global optimal. 这题的要点是local是前k个房间的最优解,这个解不一定要选第k个房间。这个local解是比较k-1的optimal和k-2 optimal + current value。之所以不以必选第k个房间作local是因为有可能最优解有连续2或多个房间不选,比如100,1,1,100

III: idea

class Solution(object):
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        def robOneDir(nums):
            pre_1 = nums[0]
            pre_2 = max(nums[0], nums[1])
            for i in range(2, len(nums)):
                cur = max(pre_2, pre_1+nums[i])
                pre_1=pre_2
                pre_2=cur
            return pre_2
        
        if not nums: return 0
        if len(nums)<2: return nums[0]
        if len(nums)==2: return max(nums[0], nums[1])
        nums1,nums2=nums[0:-1],nums[1:]
        return max(robOneDir(nums1), robOneDir(nums2))
posted @ 2016-04-09 12:02  absolute100  阅读(95)  评论(0编辑  收藏  举报