题目
当取了一个数,相邻的就没有用。
解法
f(0) = nums[0]
f(1) = max(num[0], num[1])
f(k) = max( f(k-2) + nums[k], f(k-1) )
[0]+[2]比较[1] 得到一个 [1]+[3]比较到[2]->[0]+[2]或[1]
class Solution:
def rob(self, nums):
last, now = 0, 0
for i in nums: last, now = now, max(last + i, now)
return now
效率最高
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
if len(nums) == 1:
return nums[0]
dp = [0 for i in range(len(nums))]
dp[0] = nums[0]
dp[1] = max(nums[0], nums[1])
for i in range(2, len(nums)):
dp[i] = max(nums[i]+dp[i-2], dp[i-1])
return dp[-1]