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

来源:互联网 发布:如何网络恢复mac系统 编辑:程序博客网 时间:2024/05/08 20:38

题目链接: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];        int len = nums.size();        vector<int> dp1(len+1, 0), dp2(len+1, 0);        dp1[1] = nums[0];        for(int i=1; i<len-1;i++) dp1[i+1] = max(dp1[i], dp1[i-1]+nums[i]);        for(int i=1; i<len; i++) dp2[i+1] = max(dp2[i], dp2[i-1]+nums[i]);        return max(dp1[len-1], dp2[len]);    }};


0 0
原创粉丝点击