[LeetCode] Climbing Stairs, Solution


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?
» Solve this problem

[Thoughts]
DP. The transition function should be:
 f(n) = f(n-1) + f(n-2)  n>2;
     or = 1   n=1
    or  = 2   n=2


[Code]
1:    int climbStairs(int n) {  
2:      // Start typing your C/C++ solution below  
3:      // DO NOT write int main() function  
4:      int fn_2 =1, fn_1=2;  
5:      if(n==1) return fn_2;  
6:      if(n ==2) return fn_1;  
7:      int fn;  
8:      for(int i =3; i<=n; i++)  
9:      {  
10:        fn = fn_2+fn_1;  
11:        fn_2 = fn_1;  
12:        fn_1= fn;  
13:      }  
14:      return fn;  
15:    }  


posted on   小刀初试  阅读(103)  评论(0)    收藏  举报

< 2013年1月 >
30 31 1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31 1 2
3 4 5 6 7 8 9

统计

点击右上角即可分享
微信分享提示