1. 程式人生 > >climbing-stairs-動態規劃,爬樓梯的路徑數

climbing-stairs-動態規劃,爬樓梯的路徑數

can all ase 需要 斐波那契數 bsp eps 算法復雜度 tair

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?

現在說一下大致思路:求出遞推公式

f(n)=f(n-1)+f(n-2) ===>f(n)+f(n-1)=2f(n-1)+f(n-2)

[f(n) f(n-1)]=[[1 1][1 0]][f(n-1) f(n-2)]

可以得到遞推矩陣

所以該算法的關鍵點就是:1.需要求出遞推矩陣;2.寫一個方法,能夠實現矩陣相乘

雖然代碼量會比其他幾個方法大,但是算法復雜度比較低

* 動態規劃解法
 */
public int climbStairs3(int n) {
    if (n <= 0)
        return 0;
    if (n == 1)
        return 1;
    if (n == 2)
        return 2;
 
    int[][] base = { { 1, 1 }, { 1, 0 } };
    int[][] res = matrixPower(base, n - 2);
 
    return 2*res[0][0] + res[1][0];
}
/* * 兩個矩陣相乘 */ private int[][] muliMatrix(int[][] m1, int[][] m2) { int[][] res = new int[m1.length][m2[0].length]; for (int i = 0; i < m1.length; i++) { for (int j = 0; j < m2[0].length; j++) { for (int k = 0; k < m2.length; k++) { res[i][j] += m1[i][k] * m2[k][j]; } } }
return res; }

包含三種最常用的回答,第一最優,第三最差

* 空間復雜度O(1);
 */
public int climbStairs(int n) {
    if (n < 3)
        return n;
    int one_step_before = 2;
    int two_steps_before = 1;
    int all_ways = 0;
    for (int i = 2; i < n; i++) {
        all_ways = one_step_before + two_steps_before;
        two_steps_before = one_step_before;
        one_step_before = all_ways;
    }
    return all_ways;
}
/*
 * 空間復雜度O(n);
 */
public int climbStairs_2(int n) {
    if (n < 3)
        return n;
    int[] res = new int[n + 1];
    res[1] = 1;
    res[2] = 2;
    for (int i = 3; i <= n; i++) {
        res[i] = res[i - 1] + res[i - 2];
    }
    return res[n];
}
/*
 * 方法一:遞歸 時間復雜度高
 */
public int climbStairs_1(int n) {
    if (n < 1)
        return 0;
    if (n == 1)
        return 1;
    if (n == 2)
        return 2;
    return climbStairs_1(n - 1) + climbStairs_1(n - 2);
}

斐波那契數列

class Solution {
public:
    int climbStairs(int n) {
        int f = 1;
        int g = 0;
        while(n--){
            f += g;
            g = f -g;          
        }
        return f;
    }
};

climbing-stairs-動態規劃,爬樓梯的路徑數