Description:
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.
简要题解:
采用动态规划的方法。
子问题c(i): 对于前i个房子,所能抢劫的最大金额。
第一个子问题c(0): 第0个房子的金钱数。
在解决各个子问题的过程中,需要维护两个与房子数量相同的数组: selected和notSelected。对于c(i),selected[i]表示在抢劫了第i个房子的情况下,所能抢劫的最大金额; notSelected[i]表示在补抢劫第i个房子的情况下,所能抢劫的最大金额。显然,c(i) = max(selected[i], notSelected[i])。
现在,来看看如何得到selected和notSelected的值。首先,我们有selected[0] = 第0个房子的金钱数,而notSelected[0] = 0。对于i > 0的情况,selected[i] = 第i个房子的金钱数 + notSeleted[i-1],而notSelected[i] = max(selected[i-1], notSelected[i-1])。至此,c(i)与c(i-1)间的关系也就建立起来了。接下来就是以c(0)为起点,不断地解决下一个问题。当c(i)包含了所有目标房子时,c(i)就是所要求的解。
代码:
#include<cmath>
using namespace std;
class Solution {
public:
int rob(vector<int>& nums) {
int sz = nums.size();
if (0 == sz)
return 0;
vector<int> selected(sz, 0);
vector<int> notSelected(sz, 0);
selected[0] = nums[0];
for (int i = 1; i < sz; i++) {
selected[i] = nums[i] + notSelected[i-1];
notSelected[i] = max(selected[i-1], notSelected[i-1]);
}
return max(selected.back(), notSelected.back());
}
};