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 climb to the top?
分析
题目要求给出爬到第n阶楼梯的不同方法,假设爬到第n阶楼梯有f(n)种方法,那么爬到第n阶楼梯可以由第n-1阶楼梯走一步到也可以由第n-2阶楼梯走两步到,所以有:
f(n) = f(n-1) + f(n-2)
这不就是斐波那契数列么。。。。。
源码
class Solution {
public:
int climbStairs(int n) {
int f1 = 0;
int fn = 1;
for(int i = 1; i <= n; i++){
int tmp = fn;
fn += f1;
f1 = tmp;
}
return fn;
}
};