Tutorialspoint
Problem
Solution
Submissions

Climb "n" Stairs

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C++ program to find the number of ways to climb `n` stairs using dynamic programming. You can climb either 1 or 2 stairs at a time.

Example 1
  • Input: n = 2
  • Output: 2
  • Explanation:
    • Step 1: Define the base cases: 1 way to climb 0 stairs, 1 way to climb 1 stair.
    • Step 2: For n = 2, calculate the number of ways by adding the ways to reach (n-1) and (n-2).
    • Step 3: There are 2 distinct ways to climb 2 stairs:
      1. 1 step + 1 step
      2. 2 steps at once
    • Step 4: Return the total number of ways: 2.
Example 2
  • Input: n = 3
  • Output: 3
  • Explanation:
    • Step 1: Define the base cases: 1 way to climb 0 stairs, 1 way to climb 1 stair.
    • Step 2: Calculate ways[2] = ways[1] + ways[0] = 1 + 1 = 2.
    • Step 3: Calculate ways[3] = ways[2] + ways[1] = 2 + 1 = 3.
    • Step 4: There are 3 distinct ways to climb 3 stairs:
      1. 1 step + 1 step + 1 step
      2. 1 step + 2 steps
      3. 2 steps + 1 step
    • Step 5: Return the total number of ways: 3.
Constraints
  • 1 ≤ n ≤ 45
  • Time Complexity: O(n)
  • Space Complexity: O(n)
ArraysDynamic Programming ZomatoSamsung
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use dynamic programming to solve this problem.
  • Create an array to store the number of ways to reach each step.
  • The number of ways to reach the nth step is the sum of the ways to reach the (n-1)th step and the (n-2)th step.
  • Initialize the base cases: 1 way to reach the 1st step and 2 ways to reach the 2nd step.

Steps to solve by this approach:

 Step 1: Handle base case: if n=1, return 1 directly.

 Step 2: Create a DP array of size n+1 to store number of ways to reach each step.
 Step 3: Initialize base cases: dp[1] = 1 (one way to reach first step) and dp[2] = 2 (two ways to reach second step).
 Step 4: For each step i from 3 to n, compute dp[i] = dp[i-1] + dp[i-2].
 Step 5: Return dp[n] as the result.

Submitted Code :