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?
Note: Given n will be a positive integer.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
看到这个题,首先一阵窃喜,二话不说直接写出了递归版本进行submit:
class Solution {
public int climbStairs(int n) {
if(n <= 2){
return n;
}
return climbStairs(n-1) + climbStairs(n-2);
}
}
然而只得到了Time Limit Exceeded:
分析:递归的方法是有严重的效率问题。以求解f(10)为例,需要先求f(9)和f(8),然后相加。要求f(9),需要先求f(8)和f(7)......不难发现在计算的过程中,有许多重复的计算过程,而且重复的运算会随着n的增大而急剧增加。实际上,用递归方法计算的时间复杂度是以n的指数的方式递增的。
改进:避免重复的运算。可以从左到右依次求出每一项的值,通过顺序计算求到第n项即可。显然,这种解法的时间复杂度是O(n),可以通过所有的测试用例。
class Solution {
public int climbStairs(int n) {
if(n <= 2) return n;
int preOneStep = 2;
int preTwoStep = 1;
int res = 0;
for(int i=3;i<=n;i++){
res = preOneStep + preTwoStep;
preTwoStep = preOneStep;
preOneStep = res;
}
return res;
}
}
这个问题其实考察的是斐波那契数列,只是初始项稍有不同。
数列:0,1,1,2,3,5,8,13,21,34,55,89, ··· 是在13世纪由数学家斐波那契发现的,因此被命名为斐波那契数列。
斐波那契数列解法也还有另外几种O(logn)的解法:矩阵乘法、公式法。算法较为复杂,在这里不深入分析。
解决斐波那契数列相关的问题,关键是要找到递归公式,特别注意初始项。
斐波那契数列的问题还有许多,多多练习,做到灵活应用。例如:
①不断繁殖的动物:有一种读物,出生2天后就开始以每天1只的速度繁殖后代。假设第1天,有1只这样的动物(该动物刚出生,从第三天起繁殖后代)。到第11天,共有多少只?
②摆砖头:现要将1×2大小的砖头摆放成长方形阵列。并规定长方形的纵长必须是2.假设长方形的横长为n,运用斐波那契数列则砖头的摆法为F(n+1)。