You are climbing a stair case. It takes n steps
to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
求斐波那契, f(n) = f(n-1)+f(n-2)
f(1) = 1; f(2) = 2;
1.递归,超慢
class Solution {
public:
int help(int n)
{
if(n==1)
return 1;
if(n==2)
return 2;
return help(n-1)+help(n-2);
}
int climbStairs(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
return help(n);
}
};
2.迭代
class Solution {
public:
int climbStairs(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int ret;
if(n==1)
return 1;
if(n==2)
return 2;
int x = 2;
int y = 1;
int z = 0;
int i = 2;
while( i<n)
{
z = x + y;
i ++ ;
y = x;
x = z;
}
return z;
}
};
3.矩阵公式法
A= [1 1]
[1 0]
A^n = [F(n) , F(n-1)]
[F(n-1),F(n-2)]
关键是 n为 偶数的 时候 拆分成 (A^(2\n)) ^2计算 奇数 就再乘以一个A
运算速度更快,写的不太好,可能要压栈耗费很多空间。。。
class Solution {
public:
vector<int> pow(int n){
if(n==1){
vector<int> tmp;
tmp.push_back(1);
tmp.push_back(1);
tmp.push_back(1);
tmp.push_back(0);
return tmp;
}
vector<int> tmp,tmp1;
tmp.clear();
tmp1.clear();
tmp.resize(4);
tmp1.resize(4);
tmp =pow(n>>1);
tmp1[0] = tmp[0]* tmp[0] + tmp[1] * tmp[2];
tmp1[1] = tmp[0]* tmp[1] + tmp[1] * tmp[3];
tmp1[2] = tmp1[1];
tmp1[3] = tmp[1]* tmp[2] + tmp[3] * tmp[3];
if(n%2)
{
tmp[0] = tmp1[0] + tmp1[1];
tmp[1] = tmp1[0] ;
tmp[2] = tmp1[0] ;
tmp[3] = tmp1[1] ;
return tmp;
}
return tmp1;
}
int climbStairs(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> ret;
ret.resize(4);
ret =pow(n);
return ret[0];
}
};
4.无理数公式(有精度问题)
略