Friday, September 28, 2012

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


Thoughts:
            1. 典型的 Fibonacci sequence
               F(n) = F(n -1) + F(n-2) n > 1;
               F(0) = F(1) = 1;

 
public int climbStairs(int n){
        if(n<2) return 1;
        
        return climbStairs(n-2) + climbStairs(n-1);
    }

非recursion
 
 public int climbStairs(int n) {
        if(n < 0) return 0;
        int f0 = 1, f1 = 1;
        int f2 = f0;
        
        for(int i = 2; i <= n; i++){
            f2 = f0+f1;
            f0 = f1;
            f1 = f2;
        }
        
        return f2;
    }

另外整理了别人用的code。觉得这里的int[] 用的比较巧妙
  public static int climbstairs(int n)
     {
      int[] s = {0,1,2};
    
      int number = 2;
      while (number++

No comments:

Post a Comment