Skip to content

Commit a337a8e

Browse files
authored
Create 02 - Top-Down | DP | Approach.cpp
1 parent dd889dc commit a337a8e

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution {
2+
public:
3+
// Function to recursively calculate the minimum cost to climb stairs starting from index `i`
4+
int solve(vector<int>& cost, int i, vector<int>& dp) {
5+
// Base case 1: If we are at the first step, the cost is simply the cost of step 0
6+
if (i == 0) return cost[0];
7+
// Base case 2: If we are at the second step, the cost is simply the cost of step 1
8+
if (i == 1) return cost[1];
9+
10+
// Step 3: If the result for this step is already computed (memoized), return it
11+
if (dp[i] != -1) return dp[i];
12+
13+
// Step 2: Calculate the minimum cost for the current step
14+
// Add the cost at the current step to the minimum of:
15+
// - the cost of taking 1 step back
16+
// - the cost of taking 2 steps back
17+
dp[i] = cost[i] + min(solve(cost, i - 1, dp), solve(cost, i - 2, dp));
18+
19+
// Return the memoized result
20+
return dp[i];
21+
}
22+
23+
// Main function to calculate the minimum cost to climb to the top of the stairs
24+
int minCostClimbingStairs(vector<int>& cost) {
25+
// Step 1: Create a memoization array `dp` initialized with -1
26+
// The size of `dp` is `cost.size() + 1` to handle the maximum index
27+
vector<int> dp(cost.size() + 1, -1);
28+
29+
// Start from the last two possible steps to reach the top and return the minimum
30+
return min(solve(cost, cost.size() - 1, dp), solve(cost, cost.size() - 2, dp));
31+
}
32+
};

0 commit comments

Comments
 (0)