[leetcode]Climbing Stairs

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问题;

算法思路:当最后一步跨完台阶时候,有两种跨法:一步,或者两步。因此得到状态转移方程:f(n) = f(n - 1) + f(n - 2);

【注意】直接用递归,会超时。

代码如下:

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

 

posted on 2014-07-31 23:08  喵星人与汪星人  阅读(183)  评论(0编辑  收藏  举报