198.打家劫舍
题目链接:https://leetcode.cn/problems/house-robber/
这道题目还是比较简单的,经典五部曲
class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) == 0:
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-1], dp[i-2]+nums[i])
return dp[-1]
213.打家劫舍II
题目链接:https://leetcode.cn/problems/house-robber-ii/
class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) == 0:
return 0
elif len(nums) == 1:
return nums[0]
val1 = self.robb(nums[1:])
val2 = self.robb(nums[:-1])
return max(val1, val2)
def robb(self, nums):
dp = [0] * len(nums)
dp[0] = nums[0]
for i in range(1, len(nums)):
if i==1:
dp[i] = max(dp[i-1], nums[i])
else:
dp[i] = max(dp[i-1], dp[i-2]+nums[i])
return dp[-1]
337.打家劫舍III
题目链接:https://leetcode.cn/problems/house-robber-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:
dp = self.traversal(root)
return max(dp)
def traversal(self, node):
if not node:
return (0, 0)
left = self.traversal(node.left)
right = self.traversal(node.right)
# 不偷当前节点, 偷子节点
val_0 = max(left[0], left[1]) + max(right[0], right[1])
# 偷当前节点, 不偷子节点
val_1 = node.val + left[0] + right[0]
return (val_0, val_1)