leetcode 198. House Robber ( Python )

441 阅读21分钟

描述

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

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.

解析

根据题意,整体的思路是当前房间偷和不偷两个状态,如果偷就加上前面第二个偷的商品的状态,如果不偷就是前面一个房间的状态。时间复杂度 O(N),空间复杂度O(N)。

解答

class Solution(object):
def rob(self, nums):
    """
    :type nums: List[int]
    :rtype: int
    """
    memo = [-1]*(len(nums)+1)
    def robber(nums,i):
        if i<0:
            return 0
        if memo[i] >= 0:
            return memo[i]
        result = max(robber(nums,i-2)+nums[i], robber(nums,i-1))
        memo[i] = result
        return result
    return robber(nums,len(nums)-1)                       

运行结果

Runtime: 16 ms, faster than 85.59% of Python online submissions for House Robber.
Memory Usage: 11.7 MB, less than 76.75% of Python online submissions for House Robber.
	

每日格言:成功的诀窍在于永不改动既定的方针。

请作者骑一次共享单车 支付宝

支付宝

微信

微信