You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Example 1:
Input: n = 2Output: 2Explanation: There are two ways to climb to the top.1. 1 step + 1 step2. 2 steps
Example 2:
Input: n = 3Output: 3Explanation: There are three ways to climb to the top.1. 1 step + 1 step + 1 step2. 1 step + 2 steps3. 2 steps + 1 step
上一级台阶加一
;上上一级台阶加二
;所以到达当前台阶的方法之和可以用以下式子表示: f(n) = f(n - 1) + f(n - 2)
。
因此该问题与解斐波那契数列是相同的场景。以下提供记忆化递归
与动态规划
两种解法:
const arr = [1, 2]/*** @param {number} n* @return {number}*/var climbStairs = function (n) {if (n === 1) return arr[0]if (n === 2) return arr[1]if (arr[n]) return arr[n]arr[n] = climbStairs(n - 1) + climbStairs(n - 2)return arr[n]}
/*** @param {number} n* @return {number}*/var climbStairs = function (n) {const arr = [1, 2]for (let i = 2; i < n; i++) {arr[i] = arr[i - 1] + arr[i - 2]}return arr[n - 1]}