Skip to content

Commit dc4ccda

Browse files
authored
Create 02 - Top-Down | DP | Approach.cpp
1 parent 64aed15 commit dc4ccda

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution {
2+
public:
3+
// Function to calculate the number of ways to reach the top of the stairs using memoization
4+
int solve(int n, vector<int>& dp) {
5+
// Base case: If we are at the first step (n == 0), there's exactly one way to reach the top
6+
if(n == 0) return 1;
7+
8+
// Base case: If `n` is negative, return 0 as it's an invalid path
9+
if(n < 0) return 0;
10+
11+
// If the value for this step (`n`) is already calculated and stored in `dp`, return it (Memoization)
12+
if(dp[n] != -1) return dp[n];
13+
14+
// Recursively calculate the number of ways to reach the top from the current step
15+
// We can reach step `n` by either coming from step `n-1` or step `n-2`
16+
dp[n] = solve(n - 1, dp) + solve(n - 2, dp);
17+
18+
// Return the calculated result for step `n`
19+
return dp[n];
20+
}
21+
22+
// Main function to start the process of calculating the number of ways to climb to the top
23+
int climbStairs(int n) {
24+
// Initialize a memoization array `dp` of size `n+1`, with all values set to -1
25+
// `dp[i]` will store the number of ways to reach step `i`
26+
vector<int> dp(n + 1, -1);
27+
28+
// Call the recursive function to calculate the number of ways to reach the top
29+
return solve(n, dp);
30+
}
31+
};

0 commit comments

Comments
 (0)