代码随想录算法打卡第三十三天, 新手自我记录一下刷题历程, 仅为自我打卡使用.
509. 斐波那契数
class Solution {
public:
int fib(int n) {
int first = 0;
int second = 1;
if (n < 2) return n;
int third;
for (int i = 2; i <= n; ++i) {
third = first + second;
first = second;
second = third;
}
return third;
}
};
70. 爬楼梯
class Solution {
public:
int climbStairs(int n) {
if (n < 2) return n;
int dp[n + 1];
dp[0] = 1;
dp[1] = 1;
for (int i = 2; i <= n; ++i) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
};
746. 使用最小花费爬楼梯
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
int dp[cost.size() + 1];
dp[0] = 0;
dp[1] = 0;
for (int i = 2; i < cost.size() + 1; ++i) {
dp[i] = min(dp[i - 2] + cost[i - 2], dp[i - 1] + cost[i - 1]);
}
return dp[cost.size()];
}
};
希望还能再坚持一天!