Skip to content

Commit 842ff52

Browse files
authored
Improve comments & readability in ClimbingStairs.java (#5498)
1 parent e6f597a commit 842ff52

File tree

1 file changed

+35
-11
lines changed

1 file changed

+35
-11
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,55 @@
11
package com.thealgorithms.dynamicprogramming;
22

3-
/* A DynamicProgramming solution for Climbing Stairs' problem Returns the
4-
distinct ways can you climb to the staircase by either climbing 1 or 2 steps.
5-
6-
Link : https://medium.com/analytics-vidhya/leetcode-q70-climbing-stairs-easy-444a4aae54e8
7-
*/
3+
/*
4+
* A dynamic programming solution for the "Climbing Stairs" problem.
5+
* Returns the no. of distinct ways to climb to the top
6+
* of a staircase when you can climb either 1 or 2 steps at a time.
7+
*
8+
* For example, if there are 5 steps, the possible ways to climb the
9+
* staircase are:
10+
* 1. 1-1-1-1-1
11+
* 2. 1-1-1-2
12+
* 3. 1-2-1-1
13+
* 4. 2-1-1-1
14+
* 5. 2-2-1
15+
* 6. 1-1-2-1
16+
* 7. 1-2-2
17+
* 8. 2-1-2
18+
* Ans: 8 ways
19+
*/
820
public final class ClimbingStairs {
21+
922
private ClimbingStairs() {
1023
}
1124

25+
/**
26+
* Calculates the no. of distinct ways to climb a staircase with n steps.
27+
*
28+
* @param n the no. of steps in the staircase (non-negative integer)
29+
* @return the no. of distinct ways to climb to the top
30+
* - Returns 0 if n is 0 (no steps to climb).
31+
* - Returns 1 if n is 1 (only one way to climb).
32+
* - For n > 1, it returns the total no. of ways to climb.
33+
*/
1234
public static int numberOfWays(int n) {
1335

36+
// Base case: if there are no steps or only one step, return n.
1437
if (n == 1 || n == 0) {
1538
return n;
1639
}
17-
int prev = 1;
18-
int curr = 1;
1940

20-
int next;
41+
int prev = 1; // Ways to reach the step before the current one (step 1)
42+
int curr = 1; // Ways to reach the current step (step 2)
43+
int next; // Total ways to reach the next step
2144

22-
for (int i = 2; i <= n; i++) {
45+
for (int i = 2; i <= n; i++) { // step 2 to n
2346
next = curr + prev;
24-
prev = curr;
2547

48+
// Move the pointers to the next step
49+
prev = curr;
2650
curr = next;
2751
}
2852

29-
return curr;
53+
return curr; // Ways to reach the nth step
3054
}
3155
}

0 commit comments

Comments
 (0)