刚刚做了一道很简单的题目,这次这道题目好像也是比较简单啊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?
一开始看到这道题目的时候,不知道大家会想到什么,我第一想法就是
斐波那契数列,不知道是不是之前看过类似的东西,第一反应就出来了。然后就是验证看是不是。由题意知道f(1) = 1 , f(2) = 2 ,假设n等于3,可以验证 f(3) = f(2) + f(1),当n=k时,f(k) 等于 f(k-1) 再爬一步,加上 f(k-2) 处爬两步得到,即 f(k) = f(k-1) + f(k-2),这明显就是一个斐波那契数列,问题就变成求第n个斐波那契数列的问题啦,当然啦,求数列可以用递归也可以用非递归,为了防止n很大时递归速度很慢而且调用的栈空间比较大,我这里用的是非递归。
由于程序非常简单,就直接上代码了,如下:
class Solution {
public:
int climbStairs(int n) {
if(0 >= n)
{
return 0;
}
else if(1 == n)
{
return 1;
}
int a1 = 1;
int a2 = 2;
int a3 = 2;
for(int i = 2; i < n; i++)
{
a3 = a1 + a2;
a1 = a2;
a2 = a3;
}
return a3;
}
};