[Grumpy Algorithm] LeetCode70. Climb the stairs

Suppose you are climbing stairs. It takes n steps for you to reach the top of the building.
You can climb 1 or 2 steps at a time. How many different ways can you climb to the top of a building?

0 stairs, 1 way
1 stairs, 1 way
2 stairs, 2 ways
3 stairs, 3 ways

  • The first step is to take one step, which is 2 flights of stairs (n-1).
  • Taking two steps at the first step is one flight of stairs (n-2).

n flights of stairs, the first step is to take one step + the first step is to take two steps

  • f(n) = f(n-1) + f(n-2)
/**
 * @param {number} n
 * @return {number}
 */
var climbStairs = function(n) {
    
    
    // 递归
    // if(n == 0) return 1;
    // if(n == 1) return 1;
    // return climbStairs(n-1) + climbStairs(n-2)
    
    // 迭代,动态规划(把结果缓存起来)
    const f =[]
    f[0] = 1
    f[1] = 1
    for(let i = 2; i<=n; i++){
    
    
        f[i] = f[i-1] + f[i-2]
    }
    return f[n]
};

おすすめ

転載: blog.csdn.net/qq_44721831/article/details/129858455