一、题意
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. 1 step + 1 step
2. 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
二、分析和解答
1、爬上n个台阶总共需要的ways = 爬上n-1个台阶总需的ways(再爬一阶) + 爬上n-2个台阶总需的ways(再爬两阶) 。
所以递推式就得到了:f(n) = f(n-1) + f(n-2)。n肯定得大于0的,所以前面的0,1,2必须拿出来单溜!
int climb(int n){
if(n == 0)
return 0;
if(n == 1)
return 1;
if(n == 2)
return 2;
return climb(n-1) + climb(n-2);
}
public int climbStairs(int n) {
return climb(n);
}
更简洁一些:
public int climbStairs(int n) {
if(n == 0)
return 0;
if(n == 1)
return 1;
if(n == 2)
return 2;
return climbStairs(n-1) + climbStairs(n-2);
}
提交后发现,时间超时!从代码可以看到,每一个递归里面有两个子递归,最后导致整个函数的时间复杂度达到了2^n左右。
2、优化
同样,只需要把前面已经得出来的数据记录下来,就节约了大量的资源。
public int climbStairs(int n) {
if(n == 0)
return 0;
if(n == 1)
return 1;
if(n == 2)
return 2;
int a = 1;//爬1阶所需的ways
int b = 2;//爬2阶所需的ways
int i = 3;
int res = 0;//当前的阶数
while(i <= n){
res = a + b;//爬i-2阶的ways + 爬i-1阶的ways
a = b;
b = res;
i++;
}
return res;
}
2万+


&spm=1001.2101.3001.11974&articleId=79644389&d=1&t=3&u=b3d949c9b4a64fa889bac78cbf388727)

被折叠的 条评论
为什么被折叠?



