代码随想录第三十八天|动态规划理论基础、Leetcode509. 斐波那契数、Leetcode70. 爬楼梯、Leetcode746. 使用最小花费爬楼梯
动态规划理论基础
文章链接:动态规划理论基础
大致解题流程分为以下几步:
- 确定dp数组(dp table)以及下标的含义
- 确定递推公式
- dp数组如何初始化
- 确定遍历顺序
- 举例推导dp数组
Leetcode509. 斐波那契数
题目链接:Leetcode509. 斐波那契数
最最简单的dp题目
class Solution {
public:
int fib(int n) {
if(n<=1) return n;
vector<int> dp(n+1,0);
dp[0]=0;
dp[1]=1;
for(int i=2;i<=n;i++){
dp[i]=dp[i-1]+dp[i-2];
}
return dp[n];
}
};
Leetcode70. 爬楼梯
题目链接:Leetcode70. 爬楼梯
和上一道题基本一样,尝试改为O1的空间复杂度
class Solution {
public:
int climbStairs(int n) {
if(n<=3) return n;
int pre_pre=2,pre=3,result=0;
for(int i=4;i<=n;i++){
result=pre_pre+pre;
pre_pre=pre;
pre=result;
}
return result;
}
};
Leetcode746. 使用最小花费爬楼梯
题目链接:Leetcode746. 使用最小花费爬楼梯
题目挺好,题目描述很怪
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
vector<int> dp(cost.size()+1,0);
for(int i=2;i<=cost.size();i++){
dp[i]=min(dp[i-1]+cost[i-1],dp[i-2]+cost[i-2]);
}
return dp[cost.size()];
}
};