思路:因为隔一家才能取,所以当前最大的价值要么是dp[i-2] + nums[i] 或者是 dp[i-1]
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dp = [0] * len(nums)
if (len(nums) == 1):
return nums[0]
dp[0] = nums[0]
dp[1] = max(nums[0], nums[1])
for i in range(2, len(nums)):
dp[i] = max(dp[i - 2] + nums[i], dp[i - 1])
return dp[len(nums) - 1]
思路:由于数组的尾巴和首部相连,所以尾部和首部不能同时采用。所以要拆分成两个dp来做,一个是除去首元素,另一个是除去尾元素。
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return nums[0]
dp_1 = [0] * len(nums)
dp_1[0] = nums[0]
dp_1[1] = max(nums[0], nums[1])
dp_2 = [0] * len(nums)
dp_2[1] = nums[1]
for i in range(2, len(nums) - 1):
dp_1[i] = max(dp_1[i-2] + nums[i], dp_1[i-1])
for i in range(2, len(nums)):
dp_2[i] = max(dp_2[i-2] + nums[i], dp_2[i-1])
return max(dp_1[len(nums) - 2], dp_2[len(nums) - 1])
题目链接:337. 打家劫舍 III - 力扣(LeetCode)
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dp = [0] * len(nums)
if (len(nums) == 1):
return nums[0]
dp[0] = nums[0]
dp[1] = max(nums[0], nums[1])
for i in range(2, len(nums)):
dp[i] = max(dp[i - 2] + nums[i], dp[i - 1])
return dp[len(nums) - 1]