您的位置:首页 > 其它

[leetcode] 213.House Robber II

2015-07-27 22:12 459 查看
题目:

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.

题意:

这道题是198题的延续,/article/9676029.html。不过这道题加了一个条件,就是首尾的房子也当作是相邻的。所以其实可以把环断开,因为首尾的房子最多只有一个在最终答案里。所以我们可以分成第一个房子到倒数第二个房子,或者第二个房子到最后一个房子。分别使用198题的动态规划的方法,找出较大者。

以上。

代码:

class Solution {
public:
int rob(vector<int>& nums) {
if(nums.size() == 0)return 0;
else if(nums.size() == 1)return nums[0];
return max(rob(nums,0, nums.size() - 1), rob(nums, 1, nums.size()));
}

int rob(vector<int>& nums, int start, int end) {
if(end == start + 1)return nums[start];
vector<int> DP(end - start, 0);
DP[0] = nums[start];
DP[1] = max(nums[start], nums[start + 1]);
for(int i = start + 2; i < end; i++) {
DP[i - start] = max(DP[i - start - 1], DP[i - start - 2] + nums[i]);
}
return DP[end - start - 1];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: