#70. Climbing Stairs

ยท

1 min read

https://leetcode.com/problems/climbing-stairs/description/?envType=daily-question&envId=2024-01-18


var climbStairs = function (n) {

    if (n === 1) return 1
    if (n === 2) return 2

    let first = 1, second = 2

    for (let i = 3; i <= n; i++) {
        let third = first + second
        first = second
        second = third
    }

    return second
};

To trick to solving this number is to use the Fibonacci number.

The Fibonacci number series adds numbers in a series starting from 1.

1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765...

So the number of steps needed to climb n steps is the addition n number of the Fibonacci.

The exception is 1 and 2 steps where the ways to climb such step are one and two.

So we start our loop from 3 and add up the previous two ways to climb, then we swap the second for the first and third for the second to maintain correct calculation.

Once the loop end, we return second which is the variable that stores the calculation of the last two ways to climb before the loop ended.

ย