213. House Robber II
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
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.
Example 1:
Input: [2,3,2] Output: 3 Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.
Example 2:
Input: [1,2,3,1] Output: 4 Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4.
题解:
环形数组,每次只能取不相邻的2个数,求最大和。
动态规划问题。
对于从2开始的每一个房间i,到这个房间为止能偷到的最多的钱
max_money[i] = max( max_money[i-1], max_money[i-1] + nums[i] )
当然,因为是环形数组,因此要考虑第一第二个房间和最后一个房间的关系。
我这里是直接进行了2次dp,第一次考虑如果只取第一个房间的钱,舍弃第二个房间和最后一个房间的钱。
第二次是不取第一个房间的钱,其他正常取。这样就可以覆盖全部的情况了。
class Solution(object):
def rob(self, nums):
if nums:
if(len(nums) == 1):
return nums[0]
max_money1 = [0 for i in range(len(nums))]
max_money2 = [0 for i in range(len(nums))]
max_money1[0] = nums[0]
max_money1[1] = nums[0]
max_money2[0] = 0
max_money2[1] = nums[1]
i = 2
while i < len(nums) -1:
max_money1[i] = max(max_money1[i-1], max_money1[i-2] + nums[i])
i = i+1
i = 2
while i < len(nums):
max_money2[i] = max(max_money2[i-1], max_money2[i-2] + nums[i])
i = i +1
return max(max_money1[-2], max_money2[-1])
else:
return 0
"""
:type nums: List[int]
:rtype: int
"""
本文探讨了一道经典的动态规划问题——环形房屋抢劫者II。该问题是LeetCode上的一道编程题,需要找到一种算法,在不触发报警的前提下,计算出能够从一系列环形排列的房屋中抢夺的最大金额。

745

被折叠的 条评论
为什么被折叠?



