码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode OJ:House Robber II(房屋窃贼II)

时间:2015-11-15 10:50:13      阅读:360      评论:0      收藏:0      [点我收藏+]

标签:

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.

这一题和前面的那个窃贼问题比较类似,不过这里首位同样判定是相邻的,所以这里的做法应该是先求出第一个到倒数第二个的最大值,在求出第二个到最后一个的最大值,两者较大的就是最大的值了,同样用dp来解决,代码如下所示:

class Solution {
public:
    int rob(vector<int>& nums) {
        if(!nums.size()) return 0;
        if(nums.size() == 1) return nums[0];
        vector<int> ret1, ret2;
        ret1.resize(nums.size());
        ret2.resize(nums.size());
        ret1[0] = nums[0];
        ret2[1] = nums[1];
        for(int i = 1; i < nums.size() - 1; ++i){
            ret1[i] = max((i == 1 ? 0 : ret1[i - 2]) + nums[i], ret1[i - 1]);
        }
        for(int i = 2; i < nums.size(); ++i){
            ret2[i] = max((i == 2 ? 0 : ret2[i - 2]) + nums[i], ret2[i - 1]);
        }
        return max(ret1[nums.size() - 2], ret2[nums.size() - 1]);
    }
};

 

LeetCode OJ:House Robber II(房屋窃贼II)

标签:

原文地址:http://www.cnblogs.com/-wang-cheng/p/4966188.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!