动态规划_leetcode213
Posted AceKo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了动态规划_leetcode213相关的知识,希望对你有一定的参考价值。
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
length = len(nums)
if length == 1:
return nums[0]
if length == 2:
return max(nums[0],nums[1])
if length == 3:
return max(nums[0],nums[1],nums[2])
# memo[i]考虑偷 nums[i,n]的箱子
memo = [-1 for i in range(length)]
memo[length-1] = nums[length-1]
for i in range(length-2,0,-1):
for j in range(i,length):
if j+2 < length:
memo[i] = max(memo[i],nums[j] + memo[j+2])
else:
memo[i] = max(memo[i],nums[j])
# 原问题分解为 偷两边 比较 memo[1] 和 memo[0] 的最优值
# 注意 memo[1] 的范围是 nums[1,n-1]
# memo[0] 的范围是 nums[2,n-2]
validValue = memo[1]
for i in range(length):
memo[i] = -1
memo[length-2] = nums[length-2]
for i in range(length-3,-1,-1):
for j in range(i,length-1):
if j+2 < length-1:
memo[i] = max(memo[i],nums[j] + memo[j+2])
else:
memo[i] = max(memo[i],nums[j])
return max(memo[0],validValue)
s = Solution()
# nm = [1,2,3,1]
nm = [8,2,8,9,2]
print s.rob(nm)
以上是关于动态规划_leetcode213的主要内容,如果未能解决你的问题,请参考以下文章