leetcode House Robber II

本文深入探讨了House Robber问题的延伸,即House Robber II,该问题在前者的框架上加入了环形街区的约束条件。通过分析,我们了解到如何在保持原有安全系统的前提下,巧妙地处理首尾相邻的房屋限制,进而采用分治策略解决这一复杂问题。具体而言,本文首先拆分问题,分别考虑去除首尾元素后的场景,然后利用House Robber的解决方案进行求解。最后,通过比较两种情况下的最大收益,得出最终答案。这一过程不仅展示了算法的巧妙应用,还揭示了在特定约束条件下的问题解决策略。

题目

Note: This is an extension of House Robber.

After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

题目来源:https://leetcode.com/problems/house-robber-ii/

分析

上一个题house robber的解析见:http://blog.youkuaiyun.com/u010902721/article/details/46583815

这个题在上一道题的基础上加了一个限制条件,也就是首和尾也是相邻的。那就拆开做,分别去掉第一个元素和最后一个元素后再用第一道题的方案去求解。最大值就是本题的答案。

代码

class Solution {
public:
    int rob1(vector<int>& nums, int begin, int end) {
        int size = end - begin + 1;
        if(size == 1)
            return nums[begin];
        vector<int> dp(size + 1, 0);
        dp[size-1] = nums[end];
        int ans = dp[size - 1];
        int max_next = 0;
        for(int i = end - 1; i >= begin; i--){
            dp[i - begin] = nums[i] + max_next;
            ans = max(ans, dp[i - begin]);
            max_next = max(dp[i - begin +1], max_next);
        }
        return ans;
    }

    int rob(vector<int>& nums) {
        int len = nums.size();
        if(len == 0)
            return 0;
        if(len == 1)
            return nums[0];
        return max(rob1(nums, 0, len - 2), rob1(nums, 1, len - 1));
    }
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值