Climbing Stairs

Table of contents

Problem

https://leetcode.com/problems/climbing-stairs/

You are climbing a staircase. It takes n steps to reach the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Example 1:

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

Example 2:

Input: n = 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

Constraints:

  • 1 <= n <= 45

Solution

This is a very simple combinatorics problem since number of choice that you need to take is just 2. Either you take 1 step or 2 step.

Let's say F(n) is total number of ways to reach top using n steps.

Now F(n) can be divided into 2 steps.

  1. When you start your climb with 1 step then the remaining number of ways is F(n-1)

  2. When you start your climb with 2 steps then the remaining number of ways is F(n-2)

Hence F(n) = F(n-1) + F(n-2)

If you look closely this is our standard fibonacci sequence where current value in the sequence is sum of the previous two values in the sequence.

Code

class Solution {
    public int climbStairs(int n) {

        if (n < 2) { return 1; }

        int first = 1;
        int second = 1;
        int next = 0;

        for (int i = 2; i <= n; i++)
        {
            next = first + second;
            first = second;
            second = next;
        }

        return next;
    }
}

Did you find this article valuable?

Support Pradeep Kumar's blog by becoming a sponsor. Any amount is appreciated!