213. House Robber II

Description:

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.


简要题解:

如题目所说,这是House Robber的拓展题。也就是从第0个房子和最后一个房子是不相邻的变成了是相邻的。在解法上也是在原来的基础上做一点小小的变化。为了方便读者阅读,这里先列出House Robber的题解:

采用动态规划的方法。

子问题c(i): 对于前i个房子,所能抢劫的最大金额。

第一个子问题c(0): 第0个房子的金钱数。

在解决各个子问题的过程中,需要维护两个与房子数量相同的数组: selected和notSelected。对于c(i),selected[i]表示在抢劫了第i个房子的情况下,所能抢劫的最大金额; notSelected[i]表示在补抢劫第i个房子的情况下,所能抢劫的最大金额。显然,c(i) = max(selected[i], notSelected[i])。

现在,来看看如何得到selected和notSelected的值。首先,我们有selected[0] = 第0个房子的金钱数,而notSelected[0] = 0。对于i > 0的情况,selected[i] = 第i个房子的金钱数 + notSeleted[i-1],而notSelected[i] = max(selected[i-1], notSelected[i-1])。至此,c(i)与c(i-1)间的关系也就建立起来了。接下来就是以c(0)为起点,不断地解决下一个问题。当c(i)包含了所有目标房子时,c(i)就是所要求的解。

现在,回到这个问题上。很明显,我们要想办法将环形变回非环。假设,一共有N个房子。对于整个问题,可以分成两种情况: 选择了第0个房子和没有选择第0个房子。对于选择了第0个房子,显然,第1个和第N-1个房子就不能选择了。此时,可能的最大金额数就变成了: 第2个房子到第N-2个房子所能抢劫的最大金额数+第0个房子的金钱数。 第2个房子到第N-2个房子所能抢劫的最大金额数可以用上面那个方法求解。对于没有选择第0个房子,可能的最大金额数就是 第1个房子到第N-1个房子所能抢劫的最大金额数。可以直接用上面的那个方法进行求解。最终问题的解就是这两个可能的最大金额数中的较大的那个。这样,就成功用到了上面提到的解决方法。


代码:

#include<cmath>

class Solution {
public:
    int rob(vector<int>& nums) {
        int sz = nums.size();

        if (0 == sz)
            return 0;
        else if (1 == sz)
            return nums[0];
        else if (2 == sz)
            return max(nums[0], nums[1]);

        vector<int> selected(sz, 0);
        vector<int> notSelected(sz, 0);
        int result = 0;

        // select the first house
        selected[0] = nums[2];

        for (int i = 1; i + 2 < sz - 1; i++) {
            selected[i] = nums[i+2] + notSelected[i-1];
            notSelected[i] = max(selected[i-1], notSelected[i-1]);
        }
        result = nums[0] + max(selected[sz-4], notSelected[sz-4]);

        // not selected the first house
        selected[0] = nums[1];
        for (int i = 1; i + 1 < sz; i++) {
            selected[i] = nums[i+1] + notSelected[i-1];
            notSelected[i] = max(selected[i-1], notSelected[i-1]);
        }
        result = max(result, max(selected[sz-2], notSelected[sz-2]));
        
        return result;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值