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.
解题思路
思路一:使用动态规划(DP)求解。
构造一个一维数组
dp[]
,其中
dp[i]
表示打劫了第
i
间房屋时取得的最大收益值。则状态转移方程为:
class Solution {
public:
int rob(vector<int>& nums) {
int size = nums.size();
if (size == 0) {
return 0;
}
vector<int> dp(size+1, 0);
dp[1] = nums[0];
for (int i = 2; i <= size; ++i) {
dp[i] = max(dp[i-1], dp[i-2] + nums[i-1]);
}
return dp[size];
}
};
思路二:观察上述的状态转移方程,发现求 dp[i] 时只需要前面两个元素 dp[i−1] 和 dp[i−2] 。因此,可以将上述代码的空间复杂度降低到 O(1) 。代码如下:
class Solution {
public:
int rob(vector<int>& nums) {
int size = nums.size();
if (size == 0) return 0;
int pre = nums[0], prePre = 0;
for (int i = 2; i <= size; ++i) {
int temp = max(pre, prePre + nums[i-1]);
prePre = pre;
pre = temp;
}
return pre;
}
};