Python作業(leetcode 213)
題目描述:
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]