代码随想录算法训练营第四十八天
198. 打家劫舍
代码
# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2022.12
# @Author : hello algorithm!
# @Note : https://leetcode.cn/problems/house-robber/
from typing import List
class Solution:
"""
dp[j]表示第j个房子,所抢的最大价值
dp[j] = max(dp[j-1],dp[j-2]+nums[j])
"""
def rob(self, nums: List[int]) -> int:
length = len(nums)
if length <= 2:
return max(nums)
dp = [0] * length
dp[0] = nums[0]
dp[1] = max(nums[0], nums[1])
for i in range(2, length):
dp[i] = max(dp[i - 1], dp[i - 2] + nums[i])
return dp[length - 1]
if __name__ == '__main__':
pass
213.打家劫舍II
代码
# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2022.12
# @Author : hello algorithm!
# @Note : https://leetcode.cn/problems/house-robber-ii/
from typing import List
class Solution:
def rob(self, nums: List[int]) -> int:
length = len(nums)
if length <= 2:
return max(nums)
# 考虑第一个,不抢最后一个
first = self.rob_v1(nums[:length - 1])
# 不抢第一个,考虑最后一个
last = self.rob_v1(nums[1:length])
return max(first, last)
def rob_v1(self, nums: List[int]) -> int:
length = len(nums)
if length <= 2:
return max(nums)
dp = [0] * length
dp[0] = nums[0]
dp[1] = max(nums[0], nums[1])
for i in range(2, length):
dp[i] = max(dp[i - 1], dp[i - 2] + nums[i])
return dp[length - 1]
if __name__ == '__main__':
pass
337.打家劫舍 III
代码
# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2022.12
# @Author : hello algorithm!
# @Note : https://leetcode.cn/problems/house-robber-iii/
from typing import Optional, List
# 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:
def dfs(root: Optional[TreeNode]) -> List[int]:
# 空节点
if not root:
return [0, 0]
# 叶子节点
if not root.left and not root.right:
return [0, root.val]
left = [0, 0]
right = [0, 0]
if root.left:
left = dfs(root.left)
if root.right:
right = dfs(root.right)
# 不偷root节点
not_rob = max(left) + max(right)
is_rob = root.val + left[0] + right[0]
return [not_rob, is_rob]
return max(dfs(root))
if __name__ == '__main__':
pass