題目描述:給正整數(shù) n 表示樓梯級數(shù),每次能邁一層或者兩層,問一共有多少種登頂法。
分析:基礎(chǔ)的常見題,兩種思路三種做法。到達(dá)第 n 級臺(tái)階的方法為 n - 1 級登一步,或n - 2 級登兩步。遞歸或迭代,遞歸肯定要超時(shí),迭代時(shí)間復(fù)雜度O(n),空間O(1)。第三種數(shù)學(xué)法,這個(gè)規(guī)律實(shí)際上是斐波那契數(shù)列的遞推式,可以用斐波那契通項(xiàng)公式:
迭代法:時(shí)間復(fù)雜度O(n),空間O(1)。
class Solution {
public:
int climbStairs(int n) {
if (n == 1 || n == 0) return 1;
int a = 0, b = 1;
for (int i = 1; i <= n; i ++)
{
int t = b;
b += a;
a = t;
}
return b;
}
};
迭代法二:時(shí)間復(fù)雜度O(n),空間O(n)
class Solution {
public:
int climbStairs(int n) {
vector<int> f(n + 1, 0);
f[0] = 1;
f[1] = 2;
for (int i = 2; i <= n; i++)
f[i] = f[i - 1] + f[i - 2];
return f[n];
}
};
記憶化搜索:
#include <iostream>
#include <algorithm>
#include <string>
#include <sstream>
using namespace std;
int f[100];
int fun(int x)
{
if (x == 1 || x == 0) return 1;
if (f[x] != 0) return f[x];
f[x] = fun(x - 1) + fun(x - 2);
return f[x];
}
int main()
{
f[0] = 1;
f[1] = 1;
cout<< fun(10)<<endl;
return 0;
}
斐波那契公式:時(shí)間復(fù)雜度O(1),空間O(1)。
class Solution {
public:
int climbStairs(int n) {
double x = sqrt(5);
return floor( ( pow( (1 + x) / 2, n + 1) + pow( (1 - x) / 2, n + 1) ) / x + 0.5 );
}
};