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?

 

 1 class Solution {
 2 public:
 3     int climbStairs(int n) {
 4         /**
 5          * 结题报告
 6          * 这一题是动态规划题
 7          * 后一级楼梯的上法与前面两个楼梯的上法有关
 8          * 设当前为第n阶楼梯,则有n-1阶的上法加1,和n-2阶楼梯上法加2,共两种方法,因此可以得到状态转移方程
 9          * f(n) = f(n-1) + f(n-2)
10          *
11          * 动态规划的题往往从第i个算到第n,然后内部进行状态转移方程的运算
12          * 此题还可以使用数组来存放当前阶梯的n中算法,使用数组的话会比较简单,可以返回n个阶梯的所有算法
13          * 
14          * 这一题类似菲波那切数列的O(N)算法,不使用递归,斐波那契数列可以用o(logn)来计算
15         */
16         if(n < 0)
17             return 0;
18             
19         int arr[2] = {1,2};
20         if(n<=2)
21             return arr[n - 1];
22 
23         int a = 1;
24         int b = 2;
25         
26         int res = 0;
27         for(int i = 3; i <= n; i++){
28             res = a + b;
29             a = b;
30             b = res;
31         }
32         return res;
33     }
34 };

 

posted on 2015-08-30 11:31  horizon.qiang  阅读(122)  评论(0编辑  收藏  举报

导航