题目
你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。
给定一个代表每个房屋存放金额的非负整数数组,计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。
示例
示例 1:
输入:[1,2,3,1]
输出:4
解释:偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。
偷窃到的最高金额 = 1 + 3 = 4 。示例 2:
输入:[2,7,9,3,1]
输出:12
解释:偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。
偷窃到的最高金额 = 2 + 9 + 1 = 12 。
法一:深搜
lass Solution {
public:
int dfs(int i,vector<int>& nums) {
if(i < 0) return 0;
return max(dfs(i-1,nums),dfs(i-2,nums) + nums[i]);
}
int rob(vector<int>& nums) {
int n = nums.size();
return dfs(n-1,nums);
}
};
法二:自顶向下算,递归搜索+保存计算结果=记忆化搜索
class Solution {
public:
int dfs(int i,vector<int>& nums) {
int n = nums.size();
vector<int> cache(n,-1);
int res;
if(i < 0) return 0;
if(cache[i] != -1) return cache[i];
res = max(dfs(i-1,nums),dfs(i-2,nums) + nums[i]);
cache[i] = res;
return res;
}
int rob(vector<int>& nums) {
int n = nums.size();
return dfs(n-1,nums);
}
};
法三:自底向上算,递推
class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size();
vector<int>f(n+2,0);
for(int i = 0; i < n; ++i) {
f[i+2] = max(f[i+1],f[i] + nums[i]);
}
return f[n+1];
}
};
法四:继续优化,+滚动数组
class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size();
int f0 = 0, f1 = 0, newf;
for(int x : nums) {
newf = max(f1,f0+x);
f0 = f1;
f1 = newf;
}
return f1;
}
};