[leetcode] 213. House Robber II 解题报告

题目链接:https://leetcode.com/problems/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 arearranged 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题目类似,只是这次有了环形,那么我们可以做两次动归,第一次不抢第一家的钱,则可以抢最后一家的钱。第二次抢第一家的钱,然后就不可以抢最后一家的钱,因此最后把各自最大值比较一下,返回最大的一个即是能够抢到的最多的钱。

时间复杂度为O(n),空间复杂度为O(n)。

代码如下:

class Solution {
public:
    int rob(vector<int>& nums) {
        if(nums.size() == 0)    return 0;
        if(nums.size() == 1)    return nums[0];
        vector<int> dp1(nums.size()+1, 0);
        vector<int> dp2(nums.size()+1, 0);
        dp1[1] = 0;//不拿第一个
        dp2[1] = nums[0];//拿第一个
        for(int i = 1; i < nums.size(); i++)//不拿第一个
            dp1[i+1] = max(nums[i]+dp1[i-1], dp1[i]);
        for(int i = 1; i < nums.size()-1; i++)//拿第一个
            dp2[i+1] = max(nums[i]+dp2[i-1], dp2[i]);
        
        return max(dp1[nums.size()], dp2[nums.size()-1]);
    }
};


你可能感兴趣的:(LeetCode,算法,dynamic,programming,动态规划)