1. 程式人生 > >Leetcode-House Robber

Leetcode-House Robber

闖入 ash ger tco ssi pan pro mon connect

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.

你是一名專業的強盜,計劃搶劫沿街的房屋。 每間房屋都藏有一定數量的金錢,唯一阻止你搶劫每間房屋的限制因素是鄰近的房屋有保安系統連接,如果在同一晚上有兩間相鄰的房屋被闖入,它將自動與警方聯系。

給出一份代表每個房屋的金額的非負整數列表,確定你可以在沒有提醒警方的情況下搶劫的最高金額。

 1 class Solution:
 2     def rob(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: int
 6         """
 7         last, now = 0, 0
 8         for i in nums:
 9             last, now = now, max(last + i, now)   
10         return now

規律:

f(0) = nums[0]
f(1) = max(num[0], num[1])
f(k) 
= max( f(k-2) + nums[k], f(k-1) )

Leetcode-House Robber