You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
0 commit comments