509. 斐波那契数
F(0) = 0,F(1) = 1
F(n) = F(n - 1) + F(n - 2),其中 n > 1
class Solution {
public:
int fib(int n) {
if(n==0) return 0;
if(n==1) return 1;
int x_1 = 0;
int x_2 = 1;
for(int i=2; i<=n; i++){
int temp = x_1 + x_2;
x_1 = x_2;
x_2 = temp;
}
return x_2;
}
};
70. 爬楼梯
F(1) = 1,F(2) = 2
F(n) = F(n - 1) + F(n - 2),其中 n > 1
当前台阶可以爬一个台阶 也可以是怕两个台阶上来的
所有当前的方法种类F(n)取决于 F(n - 1) + F(n - 2)
class Solution {
public:
int climbStairs(int n) {
if(n == 1) return 1;
if(n == 2) return 2;
int x_1 = 1;
int x_2 = 2;
for(int i=3; i<=n; i++){
int temp = x_1 + x_2;
x_1 = x_2;
x_2 = temp;
}
return x_2;
}
};
746. 使用最小花费爬楼梯
注意:爬到楼梯顶部是指爬到 下标cost.size()位置, 飞出数组
dp[i] 爬到第i台阶 需要的花费
dp[i] = min(dp[i-1] + cost[i-1], dp[i-2]+cost[i-2])
dp[0] = 0;
dp[1] = 0;
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
int n = cost.size();
vector<int>dp(n+1, 0);
for(int i=2; i<n+1; i++){
dp[i] = min(dp[i-1] + cost[i-1], dp[i-2]+cost[i-2]);
// cout<<dp[i]<<" ";
}
return dp[n];
}
};