Skip to content

Commit fb515a9

Browse files
authored
Create 01 - Recursive Approach.cpp
1 parent 5289d35 commit fb515a9

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// Approach 1 : Using recursion with an index (i)
2+
class Solution {
3+
public:
4+
// Function to calculate the number of ways to reach the top of the stairs starting from index `i`
5+
int calculateWays(int n, int currentStep) {
6+
// Base case: If we are at the top step (i == n), there's exactly one way to reach the top
7+
if (currentStep == n) return 1;
8+
9+
// Base case: If we've exceeded the top step (i > n), return 0 as this path is invalid
10+
if (currentStep > n) return 0;
11+
12+
// Recursively calculate the number of ways to reach the top by taking either 1 step or 2 steps at a time
13+
return calculateWays(n, currentStep + 1) + calculateWays(n, currentStep + 2);
14+
}
15+
16+
// Main function to start the process of calculating the ways to climb to the top
17+
int countWays(int n) {
18+
int currentStep = 0; // Start from the first step
19+
return calculateWays(n, currentStep); // Call the recursive function
20+
}
21+
};
22+
23+
// Approach 2 : Using recursion with step subtraction (n)
24+
class Solution {
25+
public:
26+
// Function to calculate the number of ways to reach the top from step `n`
27+
int calculateWays(int n) {
28+
// Base case: If we're already at the top (n == 0), there's exactly one way to reach the top (no steps to take)
29+
if (n == 0) return 1;
30+
31+
// Base case: If `n` is negative, it's an invalid path, return 0
32+
if (n < 0) return 0;
33+
34+
// Recursively calculate the number of ways to reach the top by subtracting either 1 step or 2 steps
35+
return calculateWays(n - 1) + calculateWays(n - 2);
36+
}
37+
38+
// Main function to start the process of calculating the ways to climb to the top
39+
int countWays(int n) {
40+
return calculateWays(n); // Call the recursive function to calculate the number of ways
41+
}
42+
};

0 commit comments

Comments
 (0)