leetcode --- js版本IT@程序员猿媛程序员

leetcode-Easy-26-DP-Climbing Sta

2019-03-30  本文已影响0人  石头说钱

题目

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梯有多少种可能

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

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

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;
};
上一篇 下一篇

猜你喜欢

热点阅读