代码随想录算法训练营第37期 第三十八天 | LeetCode509. 斐波那契数、70. 爬楼梯、746. 使用最小花费爬楼梯
一、509. 斐波那契数
解题代码C++:
class Solution {
public:int fib(int N) {if (N < 2) return N;return fib(N - 1) + fib(N - 2);}
};
题目链接/文章讲解/视频讲解:
https://programmercarl.com/0509.%E6%96%90%E6%B3%A2%E9%82%A3%E5%A5%91%E6%95%B0.html
二、70. 爬楼梯
解题代码C++:
class Solution {
public:int climbStairs(int n) {if (n <= 1) return n; // 因为下面直接对dp[2]操作了,防止空指针vector<int> dp(n + 1);dp[1] = 1;dp[2] = 2;for (int i = 3; i <= n; i++) { // 注意i是从3开始的dp[i] = dp[i - 1] + dp[i - 2];}return dp[n];}
};
题目链接/文章讲解/视频讲解:
https://programmercarl.com/0070.%E7%88%AC%E6%A5%BC%E6%A2%AF.html
三、746. 使用最小花费爬楼梯
解题代码C++:
class Solution {
public:int minCostClimbingStairs(vector<int>& cost) {vector<int> dp(cost.size() + 1);dp[0] = 0; // 默认第一步都是不花费体力的dp[1] = 0;for (int i = 2; i <= cost.size(); i++) {dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]);}return dp[cost.size()];}
};
题目链接/文章讲解/视频讲解:
https://programmercarl.com/0746.%E4%BD%BF%E7%94%A8%E6%9C%80%E5%B0%8F%E8%8A%B1%E8%B4%B9%E7%88%AC%E6%A5%BC%E6%A2%AF.html