爬楼梯
题目出处: https://leetcode-cn.com/problems/climbing-stairs/
思路:动态规划,设dp[i]为爬到第i阶有的方法数。
状态转移方程:当前若在第i阶,那么一定是从第i-1阶或者第i-2阶爬上来的。所以dp[i]=dp[i-1]+dp[i-2]
class Solution {
public:
int climbStairs(int n) {
if(n == 0){
return 0;
}else if(n == 1){
return 1;
}else if(n == 2){
return 2;
}
vector<int> dp(n+1, 0);
dp[1] = 1;
dp[2] = 2;
for(int i = 3; i <= n; ++i){
dp[i] = dp[i-1]+dp[i-2];
}
return dp[n];
}
};
使用最小花费爬楼梯
题目出处:https://leetcode-cn.com/problems/min-cost-climbing-stairs/
方法1
思路:设dp[i]是到达第i个阶梯对应的最小体力花费。
状态转移方程:dp[i]=min(dp[i-1], dp[i-2])+cost[i]
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
int n = cost.size();
vector<int> dp(n+1, 0);
dp[0] = 0;
dp[1] = cost[0]; //10
dp[2] = cost[1]; //15
for(int i = 3; i <= n; ++i){
dp[i] = min(dp[i-1], dp[i-2]) + cost[i-1];
}
return min(dp[n-1], dp[n]);
}
};
方法2
dp[i]:到达第i阶的最小花费
dp[i] = min(dp[i-1]+cost[i-1],dp[i-2]+cost[i-2])
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
int n = cost.size();
vector<int> dp(n + 1);
dp[0] = dp[1] = 0;
for (int i = 2; i <= n; i++) {
dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]);
}
return dp[n];
}
};