题目描述:
分析:先算出前几项看有没有规律可寻,果然还是有点规律的。
当n > 2时,n项等于n -1项 + n - 2项。假设 n 可以等于 0 ,并赋予它的value为 1。这不就是斐波那契数列了吗。
阶数 | 方法数 |
---|---|
1 | 1 |
2 | 2 |
3 | 3 |
4 | 5 |
5 | 8 |
方法一(递归):
这是行不通的,有超时警告
方法二(动态规划):
class Solution {
public int climbStairs(int n) {
int[] temp = new int[n+1];
temp[0] = 1;
temp[1] = 1;
for(int i = 2;i < n+1;i++){
temp[i] = temp[i - 1] + temp[i - 2];
}
return temp[n];
}
}
结果:
方法三(数学法):
百度或者谷歌斐波那契数列的公式。
公式:
代码:
class Solution {
public int climbStairs(int n) {
double an = 1/Math.sqrt(5) * (Math.pow((1+Math.sqrt(5))/2,n+1) -Math.pow((1-Math.sqrt(5))/2,n+1));
return (int) an;
}
}
结果: