198. House Robber
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
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.
class Solution {
public:
int rob(vector<int>& nums) {
int size = nums.size();
if (size == 0) return 0;
if (size == 1) return nums[0];
int* dp = new int[size];
*(dp) = nums[0];
*(dp+1) = max(nums[0], nums[1]);
for (int i = 2; i < size; i++) {
*(dp+i) = max(*(dp+i-1) , *(dp+i-2)+nums[i]);
}
return *(dp+size-1);
}
};
213. 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 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.
解:和上一题的区别是这次计算dp[size-1]时要考虑不能同时有nums[0]和nums[size-1],想到的办法是计算一个dp1[i],表示从第1家到第i+1家的最大值,这样在计算dp[size-1]时,只需要考虑1)包含第size-1家(第0家不能在内,通过dp1得到) 2)不包含size-1家 的最大值,代码:
class Solution {
public:
int rob(vector<int>& nums) {
int size = nums.size();
if (size == 0) return 0;
if (size == 1) return nums[0];
if (size == 2) return max(nums[0], nums[1]);
if (size == 3) return max(nums[0],max(nums[1],nums[2]));
int* dp = new int[size];
*(dp) = nums[0];
*(dp+1) = max(nums[0], nums[1]);
for (int i = 2; i < size-1; i++) {
*(dp+i) = max(*(dp+i-1) , *(dp+i-2)+nums[i]);
}
int* dp1 = new int[size-1];
*(dp1) = nums[1];
*(dp1+1) = max(nums[1], nums[2]);
for (int i = 3; i < size-1; i++) {
*(dp1+i-1) = max(*(dp1+i-2) , *(dp1+i-3)+nums[i]);
}
*(dp+size-1) = max(*(dp+size-2), *(dp1+size-4) + nums[size-1]);
return *(dp+size-1);
}
};