Problem
Submissions

Solution: Climbing Stairs

Statement

Naive approach

A naive approach to solve this problem would be to find all the possible ways to climb the stairs. Given that you can only climb either 11 or 22 steps at a time, we can say that the number of ways to climb nn stairs is the sum of the following:

  • the number of ways to reach the (n−1)th(n−1)^{th} stair, since we can then climb 11 step to reach the nthn^{th} stair
  • the number of ways to reach the (n−2)th(n−2)^{th} stair, since we can then climb 22 step to reach the nthn^{th} stair

We can now formulate our recursive algorithm to count the number of ways to climb nn stairs:

  • Base case 1: if n=1n = 1, there is only one way to reach the 1st1^{st} stair, which is by climbing 11 step. Therefore, we return 11.
  • Base case 2: if n=2n = 2, the total number of ways to reach the 2nd2^{nd} stair is 22 either by climbing 22 steps directly or taking 11 step two times. Therefore, we return 22.
  • Recursive case: The total number of ways that we can climb the stairs is climb_stairs(n-1) + climb_stairs(n-2)

The algorithm is based on recursion, which can potentially lead to a lot of redundant calculations. For example, when you calculate climb_stairs(n-1), it also recursively calculates climb_stairs(n-2), and when you calculate climb_stairs(n-2), it recalculates climb_stairs(n-3), and so on. This results in an exponential number of redundant calculations, making the algorithm very inefficient.

Problem
Submissions

Solution: Climbing Stairs

Statement

Naive approach

A naive approach to solve this problem would be to find all the possible ways to climb the stairs. Given that you can only climb either 11 or 22 steps at a time, we can say that the number of ways to climb nn stairs is the sum of the following:

  • the number of ways to reach the (n−1)th(n−1)^{th} stair, since we can then climb 11 step to reach the nthn^{th} stair
  • the number of ways to reach the (n−2)th(n−2)^{th} stair, since we can then climb 22 step to reach the nthn^{th} stair

We can now formulate our recursive algorithm to count the number of ways to climb nn stairs:

  • Base case 1: if n=1n = 1, there is only one way to reach the 1st1^{st} stair, which is by climbing 11 step. Therefore, we return 11.
  • Base case 2: if n=2n = 2, the total number of ways to reach the 2nd2^{nd} stair is 22 either by climbing 22 steps directly or taking 11 step two times. Therefore, we return 22.
  • Recursive case: The total number of ways that we can climb the stairs is climb_stairs(n-1) + climb_stairs(n-2)

The algorithm is based on recursion, which can potentially lead to a lot of redundant calculations. For example, when you calculate climb_stairs(n-1), it also recursively calculates climb_stairs(n-2), and when you calculate climb_stairs(n-2), it recalculates climb_stairs(n-3), and so on. This results in an exponential number of redundant calculations, making the algorithm very inefficient.