Original link: leetcode-cn.com/problems/cl…

Answer:

The problem is actually solving the Fibonacci sequence, you can refer to the problem solution [hand-drawn diagram] from recursion to dynamic programming, the problem solution is the dynamic programming solution, the following is the traversal number group solution of dynamic programming.

/ * * *@param {number} n
 * @return {number}* /
var climbStairs = function (n) {
  // Create an array of length n+1 to store the result
  let dp = new Array(n + 1).fill(0);

  F (n)=f(n-1)+f(n-2)
  The last bit of the array is the final result
  for (let i = 0; i < dp.length; i++) {
    // If I <3, the number of steps is the same as that of I
    if (i < 3) {
      dp[i] = i;
    }
    // If I >3, the current result is the sum of i-1 and i-2
    else {
      dp[i] = dp[i - 1] + dp[i - 2]; }}return dp[dp.length - 1];
};
Copy the code