【LeetCode 213】House Robber II

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(简单dp)的拓展版本,将之前一条笔直的街道改为了一条首位相连的环状街道。这就增加了一种情况:若强盗决定洗劫第一间房子,那么他就不能洗劫最后一间房子了(环嘛,首位相连的),若他不洗劫第一间房子,那么后面的房子就可以随意洗劫了。

 

class Solution {
public:

    int houseNum;//房子总数

    int smartRob(vector<int>& houses, const int start, const int stop)
    {
        //初始化dp数组及前2个房子的信息
        vector<int> dp(houseNum, 0);
        dp[0] = houses[0];
        dp[1] = houses[1];
        
        //两种情况,视start和stop的值确定,返回结果为当前洗劫模式下最大获利
        //若start == 1,则洗劫[0, houseNum-1]范围内的房间
        //若start == 2,则洗劫[1,  houseNum]范围内的房间
        for(int i = start; i < stop; i++)
            dp[i] = (i == start) ? max(dp[i-1], houses[i]):max(dp[i-1], dp[i-2] + houses[i]);
        
        return max(dp[houseNum - 2], dp[houseNum - 1]);
    }
    
    int rob(vector<int>& nums) {
    
        houseNum = nums.size();

        //两种特殊的情况,没有房子和只有一间房子
        if(houseNum == 0)
            return 0;
        if(houseNum == 1)
            return nums[0];
        
        //返回两种可能的洗劫方式中值最大的一个就是所求结果
        return max(smartRob(nums, 1, houseNum - 1), smartRob(nums, 2, houseNum));
    }
};        

 

posted @ 2015-06-17 16:33  tjuloading  阅读(187)  评论(0)    收藏  举报