House Robber II(强盗入屋 II)
【难度:Medium】
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.
给定一个整数数组(首尾相连)表示一系列连续的屋子里面放有的金钱,在不能连续进入相邻屋子抢钱的情况下求能抢到的最大金额。
解题思路
http://blog.youkuaiyun.com/qq_14821023/article/details/50880893
在198题的基础上,考虑到首尾相连的要求,将问题划分为在0~n-1和1~n两个区间动态规划,取两者中较大值。因为如果在0点抢钱的话,第n个点就不能抢;在1点抢的话,0点就不能抢。
c++代码如下:
class Solution {
public:
int rob(vector<int>& nums) {
if (nums.empty())
return 0;
int n = nums.size();
if (n == 1)
return nums[0];
return max(rob_line(nums,0,n-1),rob_line(nums,1,n));
}
int rob_line(vector<int> nums, int start, int end) {
int len = end-start+1;
int rob[len];
rob[0] = 0;
rob[1] = nums[start];
for (int i = 2; i < len; i++) {
rob[i] = (rob[i-2]+nums[i+start-1])>rob[i-1] ?(rob[i-2]+nums[i+start-1]):rob[i-1];
}
return rob[len-1];
}
};