代码随想录算法训练营第四十八天| 198. 打家劫舍,213.打家劫舍II,337.打家劫舍 III

代码随想录算法训练营第四十八天

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值