题目描述:
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.
这道题写出递推公式,赋好初值就行。一开始我的递推公式是这样的:a[i] = max{a[i-1],a[i-2]+v,a[i-3]+v}
class Solution:
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = [0] * (len(nums)+1)
max_profit = 0
if len(nums) == 0:
return 0
elif len(nums) ==1:
return nums[0]
elif len(nums) ==2:
return max(nums[1],nums[0])
else:
a[1] = nums[0]
a[2] = max(nums[1],nums[0])
for i in range(3,len(nums)+1):
a[i] = max(a[i-1],a[i-2]+nums[i-1],a[i-3]+nums[i-1])
return a[len(nums)]
但是效率只打败了33%的人,效率还是低的。然后我去看了DISCUSSION,发现我的递推公式有问题。
这是正确的递推公式:a[i] = max{a[i-1],a[i-2]+v}
改正之后,打败了67%的人。
我原本是这么想的:假设这是给定的数据集,[5,3,4,6,1,2,4],那么这里的a[6] = a[6-3]+nums[6],所以应该添加上a[i-3]+v这么一项,这项确实是冗余的。因为我的思考方式有问题。我的思考方向是:a[i]的值,考虑a[i-1]家被打劫,a[i-2]家被打劫,a[i-3]家被打劫三种情况(a[i-4]家肯定不用考虑,因为不可能有中间三家都不被打劫的情况,这样肯定取不到最大值),但是这样考虑是会重复考虑的,因为a[i-2]被打劫,那么a[i]是必然会被打劫的。a[i-2]和a[i-1]不被打劫的情况下,也就是考虑a[i-3]被打劫,那a[i]也是必然要被打劫的。
应该这么想:a[i]的取值只有两种情况,一种是被打劫,一种是不被打劫,被打劫时,a[i] = a[i-2]+v,不被打劫时,a[i] = a[i-1]