Fork me on GitHub

[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.

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

 

 

 思路:
如果没有首和尾想连的限制的话,可以得到如下递推公式: dp[i] = max(dp[i-2]+nums[i],dp[i-1]);

加上首和尾相连限制,那么也就是说首和尾最多只取一个,需要分别比较只取首或者只取尾的情况。

int rob2(vector<int>& nums,int start,int end)
    {
        int n = nums.size();
        vector<int>dp(n);
        if (start == end)return nums[start];
        if (start + 1 == end)return max(nums[start], nums[end]);         

        dp[start] = nums[start];
        dp[start + 1] = max(nums[start], nums[start+1]);

        for (int i = start+2; i <= end;i++)
        {
            dp[i] = max(dp[i-2]+nums[i],dp[i-1]);
        }

        return dp[end];
    }
    int rob2(vector<int>& nums)
    {
        int n = nums.size();
        if (nums.empty())return 0;
        if (n == 1)return nums[0];
        if (n == 2)return max(nums[0],nums[1]);
        if (n == 3)return max(nums[0], max(nums[1],nums[2]));

        //int r1 = nums[0] + rob2(nums,2,n-2);
        //int r2 = nums[1] + rob2(nums, 3, n - 1);//不对
        
        int r1 = rob2(nums, 1, n - 1);
        int r2 = rob2(nums, 0, n - 2); 
        return max(r1, r2);
    }

 

posted @ 2017-07-25 16:16  hellowOOOrld  阅读(293)  评论(0编辑  收藏  举报