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 public class Solution {
 2     public int climbStairs(int n) {
 3         // IMPORTANT: Please reset any member data you declared, as
 4         // the same Solution instance will be reused for each test case.
 5         // s(n) = s(n - 1) + s(n - 2)
 6         if(n < 1)return 0;
 7         else if(n == 1) return 1;
 8         else if(n == 2) return 2;
 9         int first = 1;
10         int second = 2;
11         int result = 0;
12         for(int i = 3; i <= n; i ++){
13             result = first + second;
14             first = second;
15             second = result;
16         }
17         return result;
18     }
19 }

 第三遍:

use only 2 constant space:

 1 public class Solution {
 2     public int climbStairs(int n) {
 3         if(n < 1) return 0;
 4         int[] result = new int[] { 1, 2 };
 5         for(int i = 2; i < n; i ++){
 6             int tmp = result[0] + result[1];
 7             result[i % 2] = tmp;
 8         }
 9         return result[(n - 1) % 2];
10     }
11 }

 

posted on 2013-11-12 14:24  Step-BY-Step  阅读(129)  评论(0编辑  收藏  举报

导航