File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
24 - Dynamic Programming Problems/04 - Ways to Reach the N'th Stair Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 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 countWays (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+ };
You can’t perform that action at this time.
0 commit comments