[LeetCode]213 强盗入屋 II

House Robber II(强盗入屋 II)

【难度:Medium】
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.
给定一个整数数组(首尾相连)表示一系列连续的屋子里面放有的金钱,在不能连续进入相邻屋子抢钱的情况下求能抢到的最大金额。


解题思路

http://blog.youkuaiyun.com/qq_14821023/article/details/50880893
在198题的基础上,考虑到首尾相连的要求,将问题划分为在0~n-1和1~n两个区间动态规划,取两者中较大值。因为如果在0点抢钱的话,第n个点就不能抢;在1点抢的话,0点就不能抢。


c++代码如下:

class Solution {
public:
    int rob(vector<int>& nums) {
        if (nums.empty())
            return 0;
        int n = nums.size();
        if (n == 1)
            return nums[0];
        return max(rob_line(nums,0,n-1),rob_line(nums,1,n));
    }
    int rob_line(vector<int> nums, int start, int end) {
        int len = end-start+1;
        int rob[len];
        rob[0] = 0;
        rob[1] = nums[start];
        for (int i = 2; i < len; i++) {
            rob[i] = (rob[i-2]+nums[i+start-1])>rob[i-1] ?(rob[i-2]+nums[i+start-1]):rob[i-1];
        }
        return rob[len-1];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值