1. 程式人生 > 其它 >leetcode 70.爬樓梯(Java)

leetcode 70.爬樓梯(Java)

技術標籤:java解leetcodeleetcodejava演算法

  1. Climbing Stairs
    You are climbing a staircase. It takes n steps to reach the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Example 1:

Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.

  1. 1 step + 1 step
  2. 2 steps
    Example 2:

Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top.
3. 1 step + 1 step + 1 step
4. 1 step + 2 steps
5. 2 steps + 1 step

class Solution {
    //應該是一個迭代的過程
    public int climbStairs(int n) {
        if(n==0) return 1;
       //爬一層,只有1種方法
       //爬兩層,兩個一步或者一個兩步,2種方法
       //爬三層,從第一層爬上來,或者從第二層上來,1+2=3種方法
       //感覺是fibonacci queue
       //使用fibonacci超時
       if(n==1) return 1;
       if(n==2) return 2;
       int p=1, q=2, result=p+q;
       for(int i=3;i<=n;i++){
           result = p+q;
           p=q;
           q=result;
       }
       return result;
    }

    // private int fibonacci(int n){
    //     if(n==1) return 1;
    //     if(n==2) return 2;
    //     return fibonacci(n-1)+fibonacci(n-2);
    // }
}