1. 程式人生 > >LeetCode刷題Easy篇爬樓梯問題(遞迴和動態規劃問題)

LeetCode刷題Easy篇爬樓梯問題(遞迴和動態規劃問題)

題目

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?

Note: Given n will be a positive integer.

Example 1:

Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2:

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

我的嘗試

感覺是個遞迴問題,但是沒有設計出遞迴方程,無法利用遞迴求解,也無法轉化為動態規劃問題。關鍵步驟沒有搞定,後來看了一下思路,明白了狀態轉化方程,

求到達n的方式有幾種,如果我們知道到達n-1有幾種方式,到達n-2有幾種方式,那麼相加就是到達n有幾種方式,因為這兩個方案沒有交集。n-1到n只能走一步,n-2到n走兩步,如果後者走1+1這種方式,那麼跟前者是重疊到。所以這兩個方案沒有交集。

來,嘗試遞迴和DP解法解決這個題目。

遞迴思路

遞迴思路:

1. 轉化方程或者說遞迴方式,理解: 1和2是基本單元,如果是5,利用基本單元可以分為(1,4),(2,3),因此遞迴方程就是

F(n)=F(n-1)+F(n-2)

2. 遞迴終止條件,如果n=1,返回1,如果n=2,則有兩種可能,返回2(2,和1,1)

3 遞迴時間複雜度較高,遞迴方式在leetcode測試test case正常,但是會超時,一般遞迴方程寫出來後,可以考慮利用DP方式解決。

class Solution {
    public int climbStairs(int n) {
        if(n==1){
            return 1;
        }
        //寫在一起,如果輸入2,返回1,不對,明確基本單元結果,明確狀態轉化方程,遞迴的核心
        if(n==2){
            return 2;
        }
        return climbStairs(n-1)+climbStairs(n-2);
        
    }
}

動態規劃方法

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

其實就是個斐波那契數列問題,梳理後另一個寫法,思路一樣:

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

節省空間的方法,最優方法:

class Solution {
    public int climbStairs(int n) {
        if(n==1) return 1;
        if(n==2) return 2;
        int one_stair=1;
        int two_stair=2;
        int ways=0;
        for (int i = 3; i <=n; i++) {
            ways=one_stair+two_stair;
            one_stair=two_stair;
            two_stair=ways;
           
        }
        return ways;
        
        
    }
}