题目描述:
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?
题目含义:
共有n层的楼梯,你每次只能走一节或者两节的楼梯,那么问你一共有多少种走法走完这n节楼梯。
解题思路:
这道题与lintcode中的111题爬楼梯一样,都属于斐波那契数列这种问题。对于这类问题而言,我们可以使用递归和循环两种方式,通常递归会比较简洁,并且更容易实现。不过,虽然递归有简洁的优点,但是它同时也有显著的缺点。递归由于是函数调用本身,而函数调用是有时间和空间的消耗的:每一次函数的调用,都需要在内存栈中分配空间以保存参数,返回地址以及临时变量,而且往栈中压入和弹出数据都需要时间;另外递归中有可能有很多计算都是重复的,从而对性能带来了很大的负面影响。但是对于递归来讲,除了效率最严重的事情就是有可能发生调用栈溢出。因此,我们选择循环来解决这个问题。
最终实现:
public class Solution {
/**
* @param n: An integer
* @return : An integer
*/
public int climbStairs (int n) {
if (n <= 0 ) {
return 1 ;
}
if (n == 1 ) {
return 1 ;
}
if (n == 2 ) {
return 2 ;
}
int firstStep = 1 ;
int secondStep = 2 ;
int currentStep = 0 ;
for (int i = 3 ; i <= n; ++i) {
currentStep = firstStep + secondStep;
firstStep = secondStep;
secondStep = currentStep;
}
return currentStep;
}
}
时间复杂度为O(n),空间复杂度为O(1)。