Skip to content

Commit b112a43

Browse files
authored
Merge pull request Dijkstra-Edu#33 from mrid88/feature/climbing-stairs
Solution Dijkstra-Edu#70 - Mridul/Edited - 16/03/2025
2 parents 0161883 + 63186d0 commit b112a43

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# Explanation of the `climbStairs` Code
2+
3+
This Java class provides a solution to the classic "Climbing Stairs" problem using dynamic programming. The goal is to determine the number of distinct ways to climb a staircase with `n` steps, where you can take either 1 step or 2 steps at a time.
4+
5+
---
6+
7+
## Class: `Solution`
8+
9+
### Method: `climbStairs(int n)`
10+
11+
#### **Purpose**
12+
This method calculates the number of ways to climb a staircase with `n` steps.
13+
14+
#### **Parameters**
15+
- `n`: An integer representing the total number of steps in the staircase.
16+
17+
#### **Logic**
18+
1. **Base Cases**:
19+
- If `n == 1`, return `1` since there is only one way to climb a single step.
20+
- If `n == 2`, return `2` since there are two ways to climb two steps: either `1+1` or `2`.
21+
22+
2. **Dynamic Programming Array**:
23+
- Create an integer array `a` of size `n`.
24+
- Initialize the first two elements:
25+
- `a[0] = 1` (1 way to climb 1 step).
26+
- `a[1] = 2` (2 ways to climb 2 steps).
27+
28+
3. **Iterative Calculation**:
29+
- Use a loop from `i = 2` to `n - 1`:
30+
- For each step `i`, calculate the number of ways to reach it as the sum of the ways to reach the previous two steps:
31+
32+
33+
\[
34+
a[i] = a[i - 1] + a[i - 2]
35+
\]
36+
37+
38+
- This is based on the observation that to reach step `i`, you can either:
39+
- Take one step from `i - 1` (contributing `a[i - 1]` ways).
40+
- Take two steps from `i - 2` (contributing `a[i - 2]` ways).
41+
42+
4. **Return Result**:
43+
- Return `a[n - 1]`, which contains the total number of ways to climb `n` steps.
44+
45+
---
46+
47+
### Example Execution
48+
#### Input:
49+
```java
50+
int n = 5;
51+
52+
Time Complexity: O(n)
53+
Space Complexity: O(n)
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution {
2+
public int climbStairs(int n) {
3+
if(n==1) return 1;
4+
5+
if(n==2) return 2;
6+
7+
int[] a = new int[n];
8+
a[0]=1;
9+
a[1]=2;
10+
11+
for(int i=2;i<n;i++){
12+
a[i]=a[i-1]+a[i-2];
13+
}
14+
return a[n-1];
15+
}
16+
}

0 commit comments

Comments
 (0)