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.
这道题目就是把根据某种规则,对一个数组进行选取元素累加,求得其最大值。这个规则就是相邻的选取元素不能含有相邻的元素。比如v = [1,7,1,8,9,0,9,0] 不能同时选取第4、5个元素。
代码实现
这道题目很明显使用的是DP,我用了一个数组存了到该元素的最大和。在计算每个元素最大和的时候,我会比较是否大于之前保留需要返回的结果,如果是就更新准备返回的值。下面的第一份代码是使用了暴力破解的方法实现。后面的是DP。
class Solution {
public:
int rob(vector<int>& nums) {
int nlen = nums.size(), res = 0;
vector<int> ttl(nlen, 0);
for(int i = 0; i < nlen; i++) {
if(i >= 2) ttl[i] = *std::max_element(ttl.begin(), ttl.begin()+i-1) + nums[i];
else ttl[i] = nums[i];
if(res < ttl[i]) res = ttl[i];
}
return res;
}
};
当然这个代码还可以简写成:
class Solution {
public:
int rob(vector<int>& nums) {
int nlen = nums.size();
vector<int> ttl(nlen, 0);
for(int i = 0; i < nlen; i++) {
if(i >= 2) ttl[i] = *std::max_element(ttl.begin(), ttl.begin()+i-1) + nums[i];
else ttl[i] = nums[i];
}
return nlen?*std::max_element(ttl.begin(), ttl.end()):0;
}
};
进一步看它的规律,发现前面的最大值部分可以在前一个或者两个地方。所以这道题目就是:
class Solution {
public:
int rob(vector<int>& nums) {
const int n = nums.size();
if (n == 0) return 0;
if (n == 1) return nums[0];
if (n == 2) return max(nums[0], nums[1]);
vector<int> f(n, 0);
f[0] = nums[0];
f[1] = max(nums[0], nums[1]);
for (int i = 2; i < n; ++i)
f[i] = max(f[i-2] + nums[i], f[i-1]);
return f[n-1];
}
};
参考:
【1】max_element: http://www.cplusplus.com/reference/algorithm/max_element/