. - 力扣(LeetCode). - 备战技术面试?力扣提供海量技术面试资源,帮助你高效提升编程技能,轻松拿下世界 IT 名企 Dream Offer。https://leetcode.cn/problems/min-cost-climbing-stairs/description/从左向右填dp表
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
int n=cost.size();//3
vector<int> dp(n+1);//4
dp[0]=dp[1]=0;
for(int i=2;i<=n;i++)//3
dp[i]=min(dp[i-1]+cost[i-1],dp[i-2]+cost[i-2]);
return dp[n];
}
};
从右向左填dp表
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
int n=cost.size();//3
vector<int> dp(n);//4
//初始化
dp[n-1]=cost[n-1],dp[n-2]=cost[n-2];
for(int i=n-3;i>=0;--i)//3
dp[i]=min(dp[i+1]+cost[i],dp[i+2]+cost[i]);//状态转移方程
return min(dp[0],dp[1]);
}
};