解法# 英文原题
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 step + 1 step
- 2 steps
Example 2: Input: 3 ; Output: 3;
Explanation: There are three ways to climb to the top.
- 1 step + 1 step + 1 step
- 1 step + 2 steps
- 2 steps + 1 step
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。示例 1:
输入: 2
输出: 2
解释: 有两种方法可以爬到楼顶。
- 1 阶 + 1 阶
- 2 阶
示例 2:
输入: 3
输出: 3
解释: 有三种方法可以爬到楼顶。
- 1 阶 + 1 阶 + 1 阶
- 1 阶 + 2 阶
- 2 阶 + 1 阶
##首先想到的解法
看到这道题目我首先想到的是一个递推的过程,
假设当前楼梯是n ;当前楼梯有多少爬法 使用 f(n)表示.
要知道当前楼梯f(n)的爬法,只需要知道前一个楼梯的爬法f(n-1),和前一阶楼梯的爬法f(n-2)
因为f(n-1)再爬一步就是 f(n)
f(n-2) 一次两步就是 f(n)
f(n) 的楼梯爬法只有这两种可能
f(n)=f(n-1)+f(n-2)
于是我就想到了递归
下面是第一中解法(C语言版)
int climbStairs(int n)
{
if( n <= 2)
{
return n;
}
else
{
return climbStairs(n-1)+climbStairs(n-2);
}
}
其他细节 由于**给定 n 是一个正整数。**所以不用考虑0 的情况
很遗憾这个做法,没能通过leetcode测试,提示的是超时, 45个用例,过了21个.说明程序本身的递推是没有问题的,程序的执行效率和环境上就要再考虑考虑了. 看到博客里面有人真就是以同样的思路做的,参考爬楼梯,而且还AC了,估计不是在leetcode上面做的,而且测试用例中输入的N比较小
至于超时得到原因是,这里使用了递归,递归会保存调用栈,一旦给的n比较大,就会造成栈击穿,从而出现错误.
将递归转换为循环
int climbStairs(int n)
{
int i =0;
int ret =0 ;
int * arr = (int *)malloc((n+1)*sizeof(int));
for ( i=0; i<=n; i++)
{
if(i <3)
{
arr[i]=i;
}
else
{
arr[i]=arr[i-1]+arr[i-2];
}
}
ret = arr[n];
free(arr);
arr=NULL;
return ret;
}
这个方法,可以通过leetcode 测试,但是N比较大的时候,还是会耗费很多堆内存,实际上每个递推过程中只和三级台阶相关,所以还可以继续优化
int climbStairs(int n)
{
int arr[3]={0,1,2};
if (n < 3)
{
return n;
}
for (int i=3; i<=n; i++)
{
arr[i%3]=arr[(i-1)%3]+arr[(i-2)%3];
}
return arr[n%3];
}
不用申请堆内存,而且栈内存只用了 3个int类型,循环存放递推的结果,大大提高了效率.