Climbing Stairs II

Climbing Stairs II_第1张图片
Climbing Stairs II.png

解題思路 :

Back Track 可以解決但是效率不夠 同樣還是使用 DP 基本跟 Climbing Stairs I 相同 先預設好 step[0] = 1 ( 題目要求 n = 0 return 1) step[1] = 1, step[2] = 2, step[3] = 4 接著就可以從 i = 4 開始 for loop 到 i <= n 關鍵就只有一句:

steps[i] = steps[i-1] + steps[i-2] + steps[i-3];

回傳最後一個值即可

C++ code :


class Solution {

public:

/**
 * @param n an integer
 * @return an integer
 */
int climbStairs2(int n) {
    // Write your code here
    vector steps(n + 1);
    steps[0] = 1;
    steps[1] = 1;
    steps[2] = 2;
    steps[3] = 4;
    for(int i = 4; i <= n; i++)
    {
        steps[i] = steps[i-1] + steps[i-2] + steps[i-3];
    }
    return steps[n];
}

};

你可能感兴趣的:(Climbing Stairs II)