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.
Example 1:
Input: [1,2,3,1] Output: 4 Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4.
Example 2:
Input: [2,7,9,3,1] Output: 12 Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12.
设dp[i]表示到第i个位置的最大收益(截止第i个、但可以第i个不选),递推表达式为:
dp[i] = max(dp[i-2] + nums[i], d[i-1])
含义就是两种情况中选最大值:
第一种情况:第i个不选,收益为截止到第i-1个的收益,即dp[i-1]
第二种情况:选第i个,那么第i-1天就不能选,之前的收益为dp[i-2]
int rob(vector<int>& nums) {
int n = (int)nums.size();
if (n == 0) {
return 0;
}
if (n == 1) {
return nums[0];
}
if (n == 2) {
return max(nums[0], nums[1]);
}
vector<int> dp(n, 0);
dp[0] = nums[0];
dp[1] = max(nums[0], nums[1]);
for (int i = 2; i < n; i++) {
dp[i] = max(dp[i-2] + nums[i], dp[i-1]);
}
return max(dp[n-2], dp[n-1]);
}
213. House Robber II
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,情况分为两种子问题,分别是:
1. 从第一个到倒数第二个之间所有房子能带来的最大收益
2. 从第二个到最后一个之间所有房子能带来的最大收益
因此,借助上面的函数,分别用两个输入数组测试得到结果,选择最大的返回就行了。
int robHelp(vector<int>& nums) {
int n = (int)nums.size();
if (n == 0) {
return 0;
}
if (n == 1) {
return nums[0];
}
if (n == 2) {
return max(nums[0], nums[1]);
}
vector<int> dp(n, 0);
dp[0] = nums[0];
dp[1] = max(nums[0], nums[1]);
for (int i = 2; i < n; i++) {
dp[i] = max(dp[i-2] + nums[i], dp[i-1]);
}
return max(dp[n-2], dp[n-1]);
}
int rob(vector<int>& nums) {
int n = (int)nums.size();
if (n == 0) {
return 0;
}
if (n == 1) {
return nums[0];
}
vector<int> a(nums.begin(), nums.end()-1), b(nums.begin()+1, nums.end());
return max(robHelp(a), robHelp(b));
}