- House Robber
(1)递归法(得到二叉树结构)
#include <iostream>
#include<vector>
using namespace std;
class Solution{
private:
int tryrob(vector<int> &nums, index) //index从哪个房子开始
{
int sum=0;
int n = nums.size();
if(index>=n) return 0;
for(int i=0; i<nums.size(); i++)
{
sum = max(sum, nums[i]+tryrob(nums, i + 2));
}
return sum;
}
public:
int rob(vector<int> &nums){ //动态数组nums中存各个房子的财富值
return tryrob(nums,0);
}
};
int main() {
return 0;
}
(2)记忆化搜索方法
#include <iostream>
#include<vector>
using namespace std;
class Solution{
private:
vector<int> memo; //memo[i] 偷窃从编号i开始的财富最大值
int tryrob(vector<int> &nums, index) //index从哪个房子开始
{
int sum=0;
int n = nums.size();
if(index>=n) return 0;
if(memo[index] != -1) return memo[index];
for(int i=index; i<nums.size(); i++)
{
sum = max(sum, nums[i]+tryrob(nums, i + 2));
}
memo[i] = sum;
return memo[i];
}
public:
int rob(vector<int> &nums){ //动态数组nums中存各个房子的财富值
memo = vector<int> (nums.size(), -1)
return tryrob(nums,0);
}
};
int main() {
return 0;
}
(3)动态规划,自底向上
#include <iostream>
#include<vector>
using namespace std;
class Solution{
public:
int rob(vector<int> &nums){ //动态数组nums中存各个房子的财富值
int n = nums.size();
vector<int> memo(n, -1);
if(n==0) return 0;
//自底向上,先计算从n-1开始偷,再逐步递推到0
memo[n-1] = nums[n-1];
for(int i=n-2; i>=0; i--)
{
//memo[i]
for(int j=i; j<=n-1; j++)
{
memo[i] = max (memo[i], nums[j]+(j+2<n ? memo[j+2] : 0));
}
}
return memo[0];
}
};
int main() {
return 0;
}