码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode 213]House Robber II

时间:2015-08-05 16:25:52      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   213   house robber ii   

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.

所有邻居围城一个圈,作为小偷的你要尽可能偷最多的钱,而不被警察发现,如果偷相邻的邻家,就会报警

有N个邻居,因为围成一个圈,所以第一户和最后一户相邻,只要求得1~N和2~N-1住户偷得钱的最大值就好

使用一个类标记到第i个住户时的最大值,并表明要不要偷这一户人家

AC代码:

class Temp{
public :
    int value;
    int number;
};

class Solution {
public:
    int cal(vector<int> &nums,int start,int stop)
    {
        Temp count[stop-start+1];
        count[0].value=nums[start];
        count[0].number=start;
        if(nums[start+1]>nums[start])
        {
            count[1].value=nums[start+1];
            count[1].number=start+1;
        }
        else
        {
            count[1].value=nums[start];
            count[1].number=start;
        }

        for(int i=start+2;i<=stop;++i)
        {
            if(count[i-start-1].number!=i-1)
            {
                count[i-start].value=count[i-start-1].value+nums[i];
                count[i-start].number=i;
            }
            else
            {
                if(nums[i]+count[i-start-2].value>count[i-start-1].value)
                {
                    count[i-start].value=nums[i]+count[i-start-2].value;
                    count[i-start].number=i;
                }
                else
                {
                    count[i-start].value=count[i-start-1].value;
                    count[i-start].number=i-start-1;
                }
            }
        }
        return count[stop-start].value;

    }
    int rob(vector<int>& nums) {
        int sum=nums.size();
        if(sum==0)
            return 0;
        if(sum==1)
            return nums[0];
        if(sum==2)
            return nums[0]>nums[1]?nums[0]:nums[1];
        int x=cal(nums,0,sum-2);
        int y=cal(nums,1,sum-1);
        return x>y?x:y;
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

[leetcode 213]House Robber II

标签:c++   leetcode   213   house robber ii   

原文地址:http://blog.csdn.net/er_plough/article/details/47298021

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!