70. Climbing Stairs: Leetcode Step-by-Step Approach

Sheefa Naaz
2 min readNov 23, 2023

--

Photo by Yan Liu on Unsplash

PROBLEM STATEMENT:

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?

APPROACH:

1. Base Cases:
— If n is less than or equal to 0, there are 0 ways (invalid case).
— If n is 1, there is only 1 way (take 1 step).
— If n is 2, there are 2 ways (take 2 steps at once or take 1 step twice).

2. Dynamic Programming:
— Initialize variables ‘one_step_before’ and ‘two_steps_before’ to represent the number of ways to reach the previous two steps.
— Initialize ‘all_ways’ to 0.
— Iterate from the third step to the target step ‘n’.
— At each step, calculate the total number of ways to reach the current step (all_ways) by adding the ways from one_step_before and two_steps_before.
— Update two_steps_before and one_step_before for the next iteration.

3. Result:
— The final result is stored in the ‘all_ways’.

#include <iostream>

class Solution {
public :
int climbStairs(int n) {
// base cases
if(n <= 0) return 0;
if(n == 1) return 1;
if(n == 2) return 2;

int one_step_before = 2;
int two_steps_before = 1;
int all_ways = 0;

for(int i=2; i<n; i++){
all_ways = one_step_before + two_steps_before;
two_steps_before = one_step_before;
one_step_before = all_ways;
}
return all_ways;
}
};

int main() {
Solution solution;

// Test cases
int n1 = 2;
int n2 = 3;

std::cout << "Ways to climb " << n1 << " stairs: " << solution.climbStairs(n1) << std::endl;
std::cout << "Ways to climb " << n2 << " stairs: " << solution.climbStairs(n2) << std::endl;

return 0;
}

TIME COMPLEXITY: O(N)

--

--

Sheefa Naaz

Passionate about Data Structures and Algorithms | Programming