周练(7)213. 打家劫舍 II

这篇博客介绍了如何用Python和C++解决经典的动态规划问题——打家劫舍II。在这个问题中,盗贼计划抢劫一排房屋,但相邻的房屋不能同时被抢劫。博主给出了两种语言的解决方案,分别使用了递归和动态规划的方法来找到最大收益。代码清晰,易于理解,适合学习动态规划的读者参考。
摘要由CSDN通过智能技术生成

#
# @lc app=leetcode.cn id=213 lang=python3
#
# [213] 打家劫舍 II
#

# @lc code=start
class Solution:
    def rob(self, nums: List[int]) -> int:
        def my_rob(nums):
            cur, pre = 0, 0
            for num in nums:
                cur, pre = max(pre + num, cur), cur
            return cur
        return max(my_rob(nums[:-1]), my_rob(nums[1:])) if len(nums) != 1 else nums[0]

# @lc code=end
  • c++版本
/*
 * @lc app=leetcode.cn id=213 lang=cpp
 *
 * [213] 打家劫舍 II
 */

// @lc code=start
class Solution {
public:
    int rob(vector<int>& nums) {
        int nlen = nums.size();
        if (nlen == 0) 
        {
            return 0;
        }
        if (nlen == 1)
        {
            return nums[0];
        }
        return max(my_rob(nums, 0, nlen-1), my_rob(nums, 1, nlen));
    }

    int my_rob(vector<int>& nums, int start, int end)
    {
        int cur = 0,  pre = 0;
        for (int i = start; i < end; i++)
        {
            int t = cur;
            cur = max(pre + nums[i], cur);
            pre = t;
        }
        return cur;
    }
};
// @lc code=end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值