[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 2013-01-27 07:14  小刀初试  阅读(102)  评论(0编辑  收藏  举报