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.
题意:给定一个 数组,要求从数组中取出一些数,使取数的和最大,要求所取得数任意两个数不能相邻。思路:动态规划。f(n) = max{ f(n-1), f(n-2)+a[n] }, f[0]=0, f[1]=a[1], 返回f(n)。
class Solution {
public:
int rob(vector<int>& nums) {
if (nums.empty()){
return 0;
}
int length = nums.size();
if (length == 1)
return nums[0];
if (length == 2){
return max(nums[0], nums[1]);
}
nums[1] = max(nums[0], nums[1]);
for (int i = 2; i < length; i++){
nums[i] = max(nums[i - 1], nums[i - 2] + nums[i]);
}
return nums[length - 1];
}
};
思路2:上一个思路是在一个数组上实现的,以下是在两个数组上实现的。
class Solution {
public:
int rob(vector<int>& nums) {
if (nums.empty()){
return 0;
}
int length = nums.size();
if (length == 1)
return nums[0];
vector<int> f(length + 1, 0);
f[1] = nums[0];
for (int i = 2; i < length+1; i++){
f[i] = max(f[i - 1], f[i - 2] + nums[i-1]);
}
return f[length];
}
};