Leetcode题目: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.

题目解答:

这个题目是之前House Robber的扩展,需要注意的是,这次的序列是一个环,同样的偷盗策略,不能连着偷窃两家。这就意味着,偷了第一家的东西,就不能偷最后一家的东西。所以,可以将下面两者的值比较一下,取出最大值即可。

(1)偷第一家,不偷最后一家;

(2)从第二家开始偷,偷到最后一家为止。

代码:

class Solution {
public:
    int rob(vector<int>& nums) {
        if(nums.size() <= 0)
            return 0;
        if(nums.size() == 1)
            return nums[0];
        if(nums.size() == 2)
            return max(nums[0], nums[1]);
        int size = nums.size();
        int left = subRob(nums, 0, size - 2);
        int right = subRob(nums, 1, size - 1);
        return max(left, right);
    }
    
    int subRob(vector<int>& nums, int start, int end) {
        int size = end - start + 1;
        vector<int> getMoney(size);
        getMoney[0] = nums[start];
        getMoney[1] = max(getMoney[0], 0 + nums[start + 1]);
        start += 2;
        for(int i = 2; i < size;i++)
        {
            getMoney[i] = max(getMoney[i - 1],getMoney[i - 2] + nums[start]);
            start++;
        }
        return getMoney[size - 1];
    }
    
    int max(int a, int b)
    {
        return a > b ? a : b;
    }
   
};

  

 

posted @ 2016-05-31 16:48  CodingGirl121  阅读(107)  评论(0编辑  收藏  举报