[LeetCode70] 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?

分类:DP

代码:

 1 class Solution {
 2 public:
 3     unordered_map<int,int> hash;
 4     int climbStairs(int n) {
 5         /*第一种方法
 6         //直接递归时间超时 
 7         //当计算f(44) = f(43) + f(42)时,需要再次计算f(42),42在计算f(43)的时候已经计算过了,所以可以用一个map存储计算过的值
 8         if(hash.find(n) != hash.end())
 9             return hash[n];
10         int result = 0;
11         if(n == 0)
12             result = 0;
13         else if(n == 1)
14             result = 1;
15         else if(n == 2)
16             result = 2;
17         else 
18             result = climbStairs(n-1) + climbStairs(n-2);
19         hash[n] = result;
20         return result;
21         */
22         
23         //第二种方法
24         vector<int> res(n,0);
25         res[0] = 1;
26         res[1] = 2;
27         for(int i = 2; i < n; ++i)
28         {
29             res[i] = res[i - 1] + res[i - 2];
30         }
31         return res[n - 1];
32     }
33 };

 

posted @ 2016-08-14 19:53  zhangbaochong  阅读(209)  评论(0)    收藏  举报