关闭

213. House Robber II

标签: leetcode
35人阅读 评论(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.

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

Subscribe to see which companies asked this question


刚开始看到这个题不知道怎么判断0和n-1个数的情况,看别的文章中说只要两次调用House Robber就好了,但是感觉还是有点别扭,不知道还有没有其他更好的解答。

class Solution {
public:
    int rob(vector<int>& nums) {
        int n=nums.size();
        if(n==0)
            return 0;
        if(n==1)
            return nums[0];
        if(n==2)
            return max(nums[0],nums[1]);
        return max(rob(nums,0,n-1),rob(nums,1,n));
        
    }

//下面就是House Robber的解答,用a表示第i-2次,b表示i-1次,省去了开一个数组保存的麻烦。
    int rob(vector<int>&nums, int start, int end)
    {
        int a=0,b=0;
        for(int i=start;i<end;i++)
        {
            int m=max(b,a+nums[i]);
            a=b;
            b=m;
        }
        return b;
    }
};

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:974次
    • 积分:92
    • 等级:
    • 排名:千里之外
    • 原创:5篇
    • 转载:4篇
    • 译文:3篇
    • 评论:0条
    文章分类
    文章存档