leetcode-Easy-26-DP-Climbing Stairs

题目

You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

爬楼梯,一次可以爬1梯,或者2梯,那么如果楼梯有n梯,那么爬到n梯有多少种可能

  • Example 1
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

  • Example 2
Input: 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

  • 思路
    当我们到达n层,可以选择从n-1层上来,也可以选择从n-2层上来,类似于斐波那契函数:
    dp[n] = dp[n-1] + dp[n-2]
  • 解法
var climbStairs = function(n) {
  if (n === 1) return 1;
  if (n === 2) return 2;

  // n等于2的时候,有2中方法【1,1】和【2】,到达梯子2层
   // n等于1的时候,有1中方法【1】到达梯子1层

  let oneStep = 2, 
  let twoSteps = 1, 
  let current;

  //到达这里,说明n>=3
  // n=3,可以从2层上来,也可以从1层上来
  for (let i = 2; i < n; i++) {
      current = oneStep + twoSteps;
      twoSteps = oneStep;
      oneStep = current;
  }
  return current;
};

你可能感兴趣的:(leetcode-Easy-26-DP-Climbing Stairs)