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

Solution 1: Recursion: TLE.

 1 public class Solution {
 2     public int climbStairs(int n) {
 3         if(n<1)
 4             return 0;
 5         if(n==1)
 6             return 1;
 7         if(n==2)
 8             return 2;
 9         return climbStairs(n-1)+climbStairs(n-2);
10     }
11 }

Solution 2: DP.

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

 

posted @ 2014-10-17 15:19  Phoebe815  阅读(128)  评论(0)    收藏  举报