
Problem
Solution
Submissions
Climbing Stairs
Certification: Basic Level
Accuracy: 100%
Submissions: 1
Points: 5
Write a Java program to solve the climbing stairs problem. 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?
Example 1
- Input: n = 2
- Output: 2
- Explanation:
- Step 1: Identify that this is a dynamic programming problem where each step depends on previous steps.
- Step 2: For n = 2, we can either take two 1-step moves or one 2-step move.
- Step 3: The two distinct ways are: [1+1] and [2].
- Step 4: Return 2 as the total number of ways to climb the staircase.
Example 2
- Input: n = 3
- Output: 3
- Explanation:
- Step 1: Apply the same dynamic programming approach for n = 3.
- Step 2: For n = 3, we can take three 1-step moves, or one 1-step and one 2-step move in different orders.
- Step 3: The three distinct ways are: [1+1+1], [1+2], and [2+1].
- Step 4: Return 3 as the total number of ways to climb the staircase.
Constraints
- 1 ≤ n ≤ 45
- You must solve this efficiently to handle large inputs
- Time Complexity: O(n)
- Space Complexity: O(1)
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
- Notice that this problem follows the Fibonacci sequence pattern
- The number of ways to reach step n is the sum of ways to reach step n-1 and step n-2
- Use dynamic programming to avoid redundant calculations
- You only need to keep track of the previous two values, not the entire array
- Initialize base cases for steps 1 and 2, then build up to n