dp[0]=nums[0]
dp[1]=max(nums[0],nums[1])
dp[i]=max(dp[i−2]+nums[i],dp[i−1])
其实这种题目的难度就在于题目描述的公式
#define MAX(x, y) ((x)>(y)?(x):(y))
class Solution {
public:
int rob(vector& nums) {
int len = nums.size();
if (len == 0)
return 0;
if (len == 1)
return nums[0];
if (len == 2)
return MAX(nums[0], nums[1]);
vector dp(len, 0);
dp[0] = nums[0];
dp[1] = MAX(nums[0], nums[1]);
for (int i = 2; i < len; i++)
dp[i] = MAX(dp[i-2] + nums[i], dp[i-1]);
return dp[len-1];
}
};
#define MAX(x, y) ((x)>(y)?(x):(y))
class Solution {
public:
int rob(vector& nums) {
int len = nums.size();
if (len == 0)
return 0;
if (len == 1)
return nums[0];
if (len == 2)
return MAX(nums[0], nums[1]);
int one = nums[0];
int two = MAX(one, nums[1]); //初始化
int max = two;
for (int i = 2; i < len; i++) {
max = MAX(one + nums[i], two);
one = two;
two = max;
}
return max;
}
};