Sunday, March 8, 2015

70. Climbing Stairs Leetcode Java

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:
It is a classic dynamic problem.
It is easy to find that, when n=2, there are 2 ways to reach the top, 0->1->2, or 0->2.
When n=3, we can either from 2->3 or from 1->3, so there are res[1]+res[2] ways to reach the top.
So the recursion equation is res[n]=res[n-1]+res[n-2] which is Fibonacci Sequence
 public int climbStairs(int n) {  
    if(n==0 || n==1) return 1;  
    int pre=1;  
    int cur=1;  
    for(int i=2;i<=n;i++){  
      int temp=cur;  
      cur=pre+cur;  
      pre=temp;  
    }  
    return cur;  
   }  

No comments:

Post a Comment