力扣第31天----第509题、第70题、第746题
一、第509题–斐波那契数
记住这五步,今天就够了–dp数组含义、递推公式、初始化、便利顺序、打印dp数组。
class Solution {
public:
int fib(int n) {
if (n < 2) return n;
int f0 = 0;
int f1 = 1;
int result = 0;
while(n > 1){
result = f0 + f1;
f0 = f1;
f1 = result;
n--;
}
return result;
}
};
二、第70题–爬楼梯
记住这五步,今天就够了–dp数组含义、递推公式、初始化、便利顺序、打印dp数组。
class Solution {
public:
int climbStairs(int n) {
if (n <3 ) return n;
int n1 = 1;
int n2 = 2;
int result = 0;
while(n>2){
result = n1 + n2;
n1 = n2;
n2 = result;
n--;
}
return result;
}
};
三、第746题–使用最小花费爬楼梯
记住这五步,今天就够了–dp数组含义、递推公式、初始化、便利顺序、打印dp数组。
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
int i0 = 0;
int i1 = 0;
int result = 0;
for (int i = 2; i <= cost.size(); i++){
result = min(i0 + cost[i-2], i1 + cost[i-1]);
i0 = i1;
i1 = result;
}
return result;
}
};