题目
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
分析
这道题其实是斐波那契数列的另一种表达方式,同时也可以利用动态规划的思想来解答。由于一次可以选择爬一级或两级台阶,要想得到登上n级台阶的方法数f(n),则可以考虑登台阶的最后一步是爬一级还是两级,也即登上台阶一共对应着两种方式:f(n-1)和爬一级台阶;f(n-2)和爬两级台阶。则很显然,f(n)=f(n-1)+f(n-2)。写到这里,感觉很熟悉,这不就是斐波那契数列的表达式嘛?是的,就是这样。
但是需要注意的是,最好不要用递归实现,因为会超时。。。
解答
class Solution { public: int climbStairs(int n) { int* way=new int[n+1]; way[0]=0; way[1]=1; way[2]=2; int methods=0; if(n==0) { methods=0; return methods; } else if(n==1){ methods=1; return methods; } else if(n==2){ methods=2; return methods; } else{ for(int i=3;i<=n;i++){ way[i]=way[i-1]+way[i-2]; } methods=way[n]; } return methods; } };
算法的时间复杂度为O(n).