509. 斐波那契数
力扣题目链接
class Solution {
public:
int fib(int n) {
if(n < 2) return n;
int dp[2];
dp[0] = 0;
dp[1] = 1;
for(int i = 2; i <= n; i++){
int sum = dp[0] + dp[1];
dp[0] = dp[1];
dp[1] = sum;
}
return dp[1];
}
};
70. 爬楼梯
力扣题目链接
class Solution {
public:
int climbStairs(int n) {
if(n < 2) return n;
vector<int> dp(n + 1);
dp[1] = 1;
dp[2] = 2;
for(int i = 3; i <= n; i++){
int sum = dp[1] + dp[2];
dp[1] = dp[2];
dp[2] = sum;
}
return dp[2];
}
};
746. 使用最小花费爬楼梯
力扣题目链接
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
vector<int> dp(cost.size());
dp[0] = cost[0];
dp[1] = cost[1];
for(int i = 2; i < cost.size(); i++){
dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i];
}
return min(dp[cost.size() - 1], dp[cost.size() - 2]);
}
};