动态规划_leetcode198拓展

#coding=utf-8
# 1
# 对状态的定义 : 考虑偷取[x...n-1]范围里的房子


class Solution1(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]

memo = [-1 for i in range(length)]
memo[length-1] = nums[length-1]

for i in range(length-2 ,-1 ,-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])

return memo[i]


# 2
# 对状态的定义: 考虑偷取[0...x]范围里的房子

class Solution2(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]

memo = [-1 for i in range(length)]
memo[0] = nums[0]

for i in range(1,length):
for j in range(i,-1,-1):

if j-2 >=0:
memo[i] = max(memo[i],nums[j] + memo[j-2])
else:
memo[i] = max(memo[i],nums[j])


return memo[length-1]


s = Solution2()
nm = [1,2,3,1]
print s.rob(nm)

猜你喜欢

转载自www.cnblogs.com/lux-ace/p/10546524.html