LearningRecord icon indicating copy to clipboard operation
LearningRecord copied to clipboard

爬楼梯

Open Rashomon511 opened this issue 5 years ago • 0 comments

假设你正在爬楼梯。需要 n 阶你才能到达楼顶。

每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶

解题思路:斐波那契数列 设跳n个台阶有f(n)种方法, 爬1个:1种 爬2个:2种 爬n个:面临两种选择: 1) 第一次爬1个,此时剩余n-1个台阶,有f(n-1)种方法 2) 第一次爬2个,此时剩余n-2个台阶,有f(n-2)种方法

        const climbStairs = (n) => {
            if (n <= 2) {
                return n
            }
            let num1 = 1;
            let num2 = 2;
            let Num = 0;
            for (let i = 2; i < n; i++) {
                numN = num1 + num2;
                num1 = num2;
                num2 = numN;
            }
            console.log(numN)
            return numN;
        } 

Rashomon511 avatar Jun 03 '19 06:06 Rashomon511