70. Climbing Stairs

Description:

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?

Note: Given n will be a positive integer.

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

My code:

/**
 * @param {number} n
 * @return {number}
 */
var climbStairs = function(n) {
    let num1 = 1, num2 = 2, temp = 0;
    if(n == 1 || n == 2) {
        return n;
    }
    for(let i = 3; i <= n; i++) {
        temp = num1 + num2;
        num1 = num2;
        num2 = temp;
    }
    return temp;
};

Note: 简单算一下前几个结果可以看出是斐波那契数列

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,522评论 0 23
  • 在微博上面发现有人晒这个炸玉米,而且看上去很好吃的样子,就想自己试一下能不能做出来。 最后发现其实做法就和做洋葱圈...
    劲纹儿的厨房阅读 6,859评论 22 69
  • 不是说要虚伪到阿谀奉承,只是人总要懂得些人情世故,哪怕你不去特意做,你也要懂。和别人交流过程中,我们总要学着怎么让...
    遇见活在当下的自己阅读 1,378评论 0 0

友情链接更多精彩内容