题意解析
说一个人爬楼梯,共有n阶。每一步可以爬1阶,或者2阶。求爬这个楼梯共有多少种不同的爬法。
Accepted Solution
有人研究了出了结论,说这个问题的解就是斐波那契数列,没错,这是结论,我们不会推结果怎么来的,只是解决问题那么就很简单了:最简单的递归案例。
本例中阶梯数n与结果的关系:
0 1 2 3 4 5 …
1 1 2 3 5 8 …
class Solution {
public:
int climbStairs(int n) {
if(n==0||n==1)
return 1;
return climbStairs(n-1)+climbStairs(n-2);
}
};
可是当n很大时,空间复杂度会很高。有人总结了斐波那契数列的通项公式
an=1/(√5)∗[(1+(√5)2)n−(1−(√5)2)n]
所以,AC解如下
class Solution {
public:
long long climbStairs(int n) {
//I find the regular pattern,and the result is fibonacci sequence,but why...
long long result=0;
//because using recursion is time exceeded when n is large,so using general formulas here
result=1.0/sqrt(5)*(pow((1+sqrt(5))/2.0,n+1)-pow((1-sqrt(5))/2.0,n+1));
return result;
}
};