[Leetcode] Climbing Stairs 爬樓梯

Climbing Stairs

You are climbing a stair case. It takes n steps to reach to the top.code

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

遞歸法

複雜度

時間 O(1.618^N) 空間 O(N)it

思路

這題幾乎就是求解斐波那契數列。最簡單的方法就是遞歸。但重複計算時間複雜度高。io

代碼

public class Solution {
    public int climbStairs(int n) {
        if(n==1 || n==0) return 1;
        else return climbStairs(n-1) + climbStairs(n-2);
    }
}

動態規劃

複雜度

時間 O(N) 空間 O(N)class

思路

將以前計算過的結果存下來,節省了一些時間。cli

代碼

public class Solution {
    public int climbStairs(int n) {
        if(n==0) return 0;
        int[] dp = new int[n+1];
        dp[0] = 1;
        dp[1] = 1;
        for(int i = 2; i <= n; i++){
            dp[i] = dp[i-1] + dp[i-2];
        }
        return dp[n];
    }
}

遞推法 Recurrance

複雜度

時間 O(N) 空間 O(1)方法

思路

實際上咱們求n的時候只須要n-1和n-2的值,因此能夠減小一些空間啊。im

代碼

public class Solution {
    public int climbStairs(int n) {
        int[] f = new int[]{0,1,2};
        if(n < 3) return f[n];
        for(int i = 2; i < n; i++){
            f[0] = f[1];
            f[1] = f[2];
            f[2] = f[0] + f[1];
        }
        return f[2];
    }
}

矩陣法

複雜度

時間 O(logN) 空間 O(1)top

相關文章
相關標籤/搜索