70. Climbing Stairs
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?
如题,n阶楼梯每次爬一层或是两层,多少种方式能到n层??
解法1:
public class Solution {
public int climbStairs(int n) {
if (n == 1 || n == 2) {
return n;
}
int f1 = 1;
int f2 = 2;
int f=0;
for(int i = 1; i < n-1; i++ ){
f = f1 + f2;
f1 = f2;
f2 = f;
}
return f;
}
}
climb to the top?
解法二:
public static int ClimbStairs(int n){
if (n == 1 || n == 2) {
return n;
}
return ClimbStairs(n-1) + ClimbStairs(n-2);
}
不解释了,哥哥还没看懂,看起来是一个斐波那契数列问题!
解题思路:
首先可以看出这是一个爬楼梯问题,n阶楼梯,每次选择一阶或是两阶。这样,爬到最后一阶是有两种情况,第一种情况是从第n-1 阶 爬一阶,第二种情况是从第n-2阶
爬两阶,也就是这两种情况。即如果要爬n阶楼梯,他的方法是爬n-1阶的方法数加上n-2阶的方法数,故此可以知道,这是一个典型的斐波那契数列问题,上面的解法
二出现的问题是‘超时’,第一种解法很好的解决了这个问题,就是这样。