Climbing Stairs

Link:http://oj.leetcode.com/problems/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     HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
 3     public int climbStairs(int n) {
 4         if (n == 1 || n == 0)
 5             return 1;
 6         int steps = 0;
 7         int step1 = 0;
 8         int step2 = 0;
 9         //using memorized recursion
10         if (map.containsKey(n - 1))
11             step1 = map.get(n - 1);
12         else
13             step1 = climbStairs(n - 1);
14         if (map.containsKey(n - 2))
15             step2 = map.get(n - 2);
16         else
17             step2 = climbStairs(n - 2);
18         steps += step1 + step2;
19         map.put(n - 1, step1);
20         map.put(n - 2, step2);
21         return steps;
22     }
23 }

 

 

posted on 2014-05-05 05:34  Atlas-Zzz  阅读(137)  评论(0编辑  收藏  举报

导航