关于此题我的往期文章:
leetCode 746. 使用最小花费爬楼梯 动态规划-CSDN博客https://heheda.blog.csdn.net/article/details/133325840
- dfs(i-1) 跳到 dfs(i) 需要花费 dfs(i-1) + cost[i-1]
- dfs(i-2) 跳到 dfs(i) 需要花费 dfs(i-2) + cost[i-2]
(1) 递归(超时)
class Solution {
public:
// 递归(超时)
int minCostClimbingStairs(vector<int>& cost) {
int n = cost.size();
function<int(int)> dfs=[&](int i) -> int{
if(i==0 || i==1) return 0;
return min(dfs(i-1)+cost[i-1],dfs(i-2)+cost[i-2]);
};
return dfs(n);
}
};
(2)递归搜索 + 保存计算结果 = 记忆化搜索
class Solution {
public:
// 记忆化搜索
int minCostClimbingStairs(vector<int>& cost) {
int n = cost.size();
vector<int> memo(n+1,-1);
function<int(int)> dfs=[&](int i) -> int{
if(i==0 || i==1) return 0;
int& res = memo[i];
if(res != -1) return res;
return res = min(dfs(i-1)+cost[i-1],dfs(i-2)+cost[i-2]);
};
return dfs(n);
}
};
(3)1:1 翻译成递推
class Solution {
public:
// 递推
int minCostClimbingStairs(vector<int>& cost) {
int n = cost.size();
vector<int> f(n+1,0);
for(int i=0;i<=n-2;i++) {
f[i+2] = min(f[i+1]+cost[i+1],f[i]+cost[i]);
}
return f[n];
}
};
class Solution {
public:
// 递推
int minCostClimbingStairs(vector<int>& cost) {
int n = cost.size();
vector<int> f(n+1,0);
f[0]=0;
f[1]=0;
for(int i=2;i<=n;i++) {
f[i] = min(f[i-1]+cost[i-1],f[i-2]+cost[i-2]);
}
return f[n];
}
};
- 空间优化
class Solution {
public:
// 递推 + 空间优化
int minCostClimbingStairs(vector<int>& cost) {
int n = cost.size();
vector<int> f(2,0);
f[0]=0;
f[1]=0;
for(int i=2;i<=n;i++) {
f[i%2] = min(f[(i-1)%2]+cost[i-1],f[(i-2)%2]+cost[i-2]);
}
return f[n%2];
}
};
class Solution {
public:
// 递推 + 空间优化
int minCostClimbingStairs(vector<int>& cost) {
int n = cost.size();
int f0=0,f1=0;
for(int i=2;i<=n;i++) {
int tmp = min(f1+cost[i-1],f0+cost[i-2]);
f0 = f1;
f1 = tmp;
}
return f1;
}
};
我的往期文章推荐:
LeetCode 70.爬楼梯 + 记忆化搜索 + 递推 + 动态规划 + 空间优化-CSDN博客https://blog.csdn.net/weixin_41987016/article/details/134192204?spm=1001.2014.3001.5501leetCode 746. 使用最小花费爬楼梯 动态规划-CSDN博客https://heheda.blog.csdn.net/article/details/133325840leetCode 198.打家劫舍 动态规划入门:从记忆化搜索到递推-CSDN博客https://blog.csdn.net/weixin_41987016/article/details/134179583?spm=1001.2014.3001.5501