内容:
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:
Solution(){
memset(F, 0, sizeof(int)*N*3);
}
int rob(vector<int> &num) {
if(num.size() == 0) return 0;
else if(num.size() == 1) return num[0];
else{
// 初始化第一行
F[0][0] = 0;
F[0][1] = num[1];
F[0][2] = num[0];
int maxMoney = max(num[1], num[0]);
for(int i = 1; i < num.size()-1; i++){
for(int j = 0; j < 3; j++){
int t = j >> 1;
for(int k = 0; k < 3; k++){
if( t == (k & (1>>0))){ // 判断第i行状态j与第i-1行各个状态是否兼容 即j的倒数第二位与k的倒数第一位是否相同
F[i][j] = max(F[i-1][k], F[i][j]); // 输出兼容的最大者
}
}
if((j & (1<<0)) == 1) F[i][j] = F[i][j] + num[i+1]; // 如果状态j最后一位为1则 需要加上该方案数
if(F[i][j] > maxMoney){ // 求最大的方案数
maxMoney = F[i][j];
}
}
}
return maxMoney;
}
}
private:
int F[N][3];
};
该题是一道简单动态规划相关的题目,如果能够正确地找到其中的递推关系,那么该题就很容易了。对于n个数的数组,如果要求得其连续不相邻元素的最大值,那么我们只需求得n-1个数的最大值,以及求得n-2个数的最大值即可,这样就形成了求解该问题的子问题的最大值问题,所以很容易考虑出递推关系,假设数组为Arr[],n个数的数组对应的不相邻连续元素的最大值用函数f(n)表示,则有f(n) = max{f(n-1), f(n-2)+A[n-1]},其中n>=2,f(n)也称为递推关系。其中f(n-1)为n-1个元素的最大值,f(n-2)+Arr[n-1]为n-2个元素的最大值加上数组第n个元素的值,因为要求元素不能相邻,所以会跳过第n-1个元素,这个应该很好理解。