
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 step + 1 step
- 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 step + 1 step + 1 step
- 1 step + 2 steps
- 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)
Editorial
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. |
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.