目录
198.打家劫舍
题意:nums中不能取相邻的数,求能取到的最大总和
class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) == 1: #因为题目提示1 <= nums.length <= 100,所以不需要考虑nums为空的情况
return nums[0]
dp = [0] * len(nums)
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[-1]
213.打家劫舍II
题意:把上题改为环形,即首尾不可以同时取
方法:复用上题代码,分别求不包含首、不包含尾的范围中得到的值,再合并提取最大值
class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
left = self.rob1(nums[:-1])
right = self.rob1(nums[1:])
return max(left, right)
def rob1(self, nums: List[int]) -> int:
if not nums:
return 0
elif len(nums) == 1:
return nums[0]
dp = [0] * len(nums)
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[-1]
337.打家劫舍III
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def rob(self, root: Optional[TreeNode]) -> int:
dproot = self.robtree(root)
return max(dproot[0], dproot[1])
def robtree(self, cur):
if not cur:
return [0,0]
dpleft = self.robtree(cur.left) #记录左孩子情况
dpright = self.robtree(cur.right) #记录右孩子情况
dp0 = max(dpleft[0], dpleft[1]) + max(dpright[0], dpright[1]) #不偷当前节点=左孩子取最大情况+右孩子取最大情况
dp1 = cur.val + dpleft[0] + dpright[0] #偷当前节点=当前节点值+不偷左孩子的情况+不偷右孩子的情况
return [dp0, dp1]