题目描述:
Note: This is an extension of House Robber.
After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.
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. 先不考虑环的情况,即先处理此题的原始版本
2. 求解无环时,问题的关键在于针对某一间房子抢和不抢的选择。
假如要抢第i个, 就不能抢第i+1个;
假如不抢第i个,那么可以选择抢或者不抢第i+1个
很明显,这是一个动态规划问题。
3. 可以设定数组result[],result[i]表示到该房子时最优选择下的金钱数
4. 加上环的条件后,考虑两种情况即可。第一是抢了第一家,不抢最后一家,第二是不抢第一家,即分别计算抢了2-n和抢了1-n-1的情况,取最大值就是结果
动态算法:
result[i] = max(result[i - 1], result[i - 2] + nums[i]);
代码如下:
class Solution(object):
def rob(self, nums):
""" :type nums: List[int] :rtype: int """
length=len(nums)
if length==0:
return 0
elif length==1:
return nums[0]
elif length==2:
return max(nums[0],nums[1])
return max(self.dp(nums[1:]),self.dp(nums[:-1]))
def dp(self,nums):
if len(nums)==2:
return max(nums[0],nums[1])
result=[0 for each in nums]
result[0]=nums[0]
result[1]=max(nums[0],nums[1])
for i in range(2,len(nums)):
result[i]=max(result[i-2]+nums[i],result[i-1])
return result[len(nums)-1]