2.Climbing Stairs

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?

Climbing stairs follows Fibonacci series approach.

class Solution
{
public:
    int climbStairs(int n)
    {

        if(n==1){return 1;}
        int a = 1, b = 1, s = 0;
        

        for (int i = 2; i <= n; i++)
        {
            s = a + b;
            a = b;
            b = s;
        }

        return s;
    }
};

Count ways to N'th Stair(Order does not matter)

Order does not matter means for n=4 {1 2 1},{2 1 1},{1 1 2} are considered same.

Solution:

Approach Count increases when number are even

class Solution
{
public:
    //Function to count number of ways to reach the nth stair
    //when order does not matter.
    long long countWays(int n)
    {
        // your code here
        long long int count = 1;
        for (int i = 1; i <= n; i++)
        {
            if (i % 2 == 0)
            {
                count++;
            }
        }

        return count;
    }
};

Last updated