House Robber II

25 篇文章 0 订阅

题目

原题

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.

思路

这道题是House Robber(链接:https://leetcode.com/problems/house-robber/)的升级版本.
即所给定的nums构成了环.
由于每个house最多被rob一次, 设len=nums.size(),
所以这个环只对nums[0]和nums[len-1]起作用.
即如果选择了nums[0], 就不能选择了nums[len-1];
如果选择了nums[len-1], 就不能选择nums[0].
所以该问题就变了了House Robber的两个子问题的结果最大值.
ans=max(rob(nums[0,...,len-2), rob(nums[1,...,len-1)). 
其中rob为House Robber问题的解.
具体看代码.

code

class Solution {
public:
    int rob_helper(const vector<int>& nums, const int s, const int e) {
        int len = e - s + 1;
        vector<int>res(len, 0);
        res[0] = nums[s];
        res[1] = max(nums[s], nums[s + 1]);
        for(int i = s + 2; i <= e; i++) {
            res[i - s] = max(res[i - s - 2] + nums[i], res[i - s - 1]);
        }
        return res[len - 1];
    }

    int rob(vector<int>& nums) {
        int len = nums.size();
        if(len <= 0) return 0;
        if(len <= 1) return nums[0];
        // Include the first one of nums without the last one.
        int f = rob_helper(nums, 0, len - 2);
        // Include the last one of nums without the first
        int s = rob_helper(nums, 1, len - 1);
        return max(f, s);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值