|
1 | 1 | package com.thealgorithms.dynamicprogramming;
|
2 | 2 |
|
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 | + */ |
8 | 20 | public final class ClimbingStairs {
|
| 21 | + |
9 | 22 | private ClimbingStairs() {
|
10 | 23 | }
|
11 | 24 |
|
| 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 | + */ |
12 | 34 | public static int numberOfWays(int n) {
|
13 | 35 |
|
| 36 | + // Base case: if there are no steps or only one step, return n. |
14 | 37 | if (n == 1 || n == 0) {
|
15 | 38 | return n;
|
16 | 39 | }
|
17 |
| - int prev = 1; |
18 |
| - int curr = 1; |
19 | 40 |
|
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 |
21 | 44 |
|
22 |
| - for (int i = 2; i <= n; i++) { |
| 45 | + for (int i = 2; i <= n; i++) { // step 2 to n |
23 | 46 | next = curr + prev;
|
24 |
| - prev = curr; |
25 | 47 |
|
| 48 | + // Move the pointers to the next step |
| 49 | + prev = curr; |
26 | 50 | curr = next;
|
27 | 51 | }
|
28 | 52 |
|
29 |
| - return curr; |
| 53 | + return curr; // Ways to reach the nth step |
30 | 54 | }
|
31 | 55 | }
|
0 commit comments