算法训练Day33 |● 509. 斐波那契数 ● 70. 爬楼梯 ● 746. 使用最小花费爬楼梯
509. 斐波那契数
class Solution {
public:int fib(int n) {if(n<=1) return n;int pre2 = 0;int pre1 = 1;int result = 0;for(int i=2; i<=n; i++ ){result = pre1+pre2;pre2 = pre1;pre1 = result;}return result;}
};
参考文章:代码随想录- 509. 斐波那契数
70. 爬楼梯
class Solution {
public:int climbStairs(int n) {if(n<=3) return n;int dp[2];dp[0] = 2;dp[1] = 3;int result;for(int i=4; i<=n; i++){result = dp[0]+dp[1];dp[0]=dp[1];dp[1] = result;}return result;}
};
参考文章:代码随想录-70. 爬楼梯
746. 使用最小花费爬楼梯
class Solution {
public:int minCostClimbingStairs(vector<int>& cost) {if(cost.size()==2) return min(cost[0], cost[1]);int all_cost = 0;vector<int> dp(cost.size()+1);dp[0] = 0;dp[1] = 0;for(int i=2; i<dp.size(); i++){dp[i] = min(dp[i-2]+cost[i-2], dp[i-1]+cost[i-1]);}return dp[dp.size()-1];}
};
参考文章:代码随想录- 746. 使用最小花费爬楼梯