LintCode: Climbing Stairs

C++

 1 class Solution {
 2 public:
 3     /**
 4      * @param n: An integer
 5      * @return: An integer
 6      */
 7     int climbStairs(int n) {
 8         // write your code here
 9         // f(0) = 1; 
10         // f(1) = 1; 
11         // f(2) = 2;
12         // f(n) = f(n-1) + f(n-2) n>2;
13         if (n == 2) {
14             return 2;
15         }
16         if (n == 0 || n == 1) {
17             return 1;
18         }
19         int a=1, b=2;
20         //int c;
21         for (int i=3; i<=n; i++) {
22             b = a + b;
23             a = b - a;
24             // c = a + b;
25             // a = b;
26             // b = c;
27         }
28         return b;
29     }
30 };

 

posted @ 2015-11-27 00:45  ZH奶酪  阅读(251)  评论(0编辑  收藏  举报