今日总结:
动规五部曲:
1). 确定dp数组下标及其含义;
2). 确定递推公式;
3). 初始化;
4). 遍历顺序;
5). 打印dp数组;
509. 斐波那契数
class Solution {
public:
int fib(int n) {
//dp数组的下标及其实际含义
//递推公式
//初始化
//遍历顺序
//打印数组
if(n==0) return 0;
if(n==1) return 1;
vector<int> dp(n+1);
dp[0]=0;
dp[1]=1;
for(int i=2;i<=n;i++){
dp[i]=dp[i-1]+dp[i-2];
}
return dp[n];
}
};
70. 爬楼梯
class Solution {
public:
int climbStairs(int n) {
//dp数组下标及其含义
if(n==0||n==1) return 1;
if(n==2) return 2;
//递推公式
vector<int> dp(n+1);
dp[0]=1;
dp[1]=1;
dp[2]=2;
//初始化
//遍历顺序
for(int i=3;i<=n;i++){
dp[i]=dp[i-1]+dp[i-2];
}
return dp[n];
}
};
746. 使用最小花费爬楼梯
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
//dp数组下标及其含义:爬上第i个楼梯所需要的最少费用
if(cost.size()==0) return 0;
if(cost.size()==1) return cost[0];
if(cost.size()==2) return min(cost[0],cost[1]);
vector<int> dp(cost.size()+1);
//递推公式:min(爬上第i-2个台阶的最小费用+cost[i-2], 爬上第i-1个台阶的最小费用+cost[i-1])
//dp数组初始化
dp[0]=0;
dp[1]=0;
dp[2]=min(cost[0],cost[1]);
for(int i=2;i<=cost.size();i++){
dp[i]=min(dp[i-2]+cost[i-2],dp[i-1]+cost[i-1]);
}
return dp[cost.size()];
}
};