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:
1 2 3 4 5 6
Input: n = 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
思路
DP 的重點就是找規律,所以通常我會先沙盤推演一波找規律,如果我沒有什麼想法的話。
下面是我沙盤推演 test case 從 1 ~ 6
1// n = 1, ans count = 1 1 2// n = 2, ans count = 2 112 3// n = 3, ans count = 3 1111221 4// n = 4, ans count = 5 從這步開始可以看出他有斐波那契的跡象 111121112111222 5// n = 5, ans count = 8 111112111121111211112221212122 6// n = 6, ans count = 13 1111112111112111112111112111112221121212112122111221212222
functionclimbStairs(n: number): number { /** * a = ans when one stair * b = ans when two stairs * count = fibonacci count when n stairs */ let a = 1, b = 2, count = 0;
// base case if (n === a || n === b) return n;
// starting with three stairs for (let i = 3; i < n + 1; i++) { /** * a position = i - 2 = 1 * b position = i - 1 = 2 * count position will be 3 when take count. */ // count when three stairs will equal to a plus b (fibonacci) count = a + b;
// set a position to b a = b;
// set b position to count position. b = count; } return count; };