Skip to content

Commit dd889dc

Browse files
authored
Create 01 - Recursive Approach (LTE caused).cpp
1 parent caf68cd commit dd889dc

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// Approach 1 : Starting from the Beginning of the Stairs
2+
class Solution {
3+
public:
4+
// Recursive function to calculate the minimum cost to climb stairs starting from index `i`
5+
int solve(vector<int>& cost, int i) {
6+
// Base case: If `i` exceeds the last index, there is no cost
7+
if (i >= cost.size()) return 0;
8+
9+
// Recursive case: Add the cost at the current step and calculate the minimum cost
10+
// of taking either 1 or 2 steps from the current position
11+
return cost[i] + min(solve(cost, i + 1), solve(cost, i + 2));
12+
}
13+
14+
// Function to calculate the minimum cost to reach the top starting from step 0 or step 1
15+
int minCostClimbingStairs(vector<int>& cost) {
16+
// Start climbing from step 0 or step 1, and take the minimum of the two
17+
return min(solve(cost, 0), solve(cost, 1));
18+
}
19+
};
20+
21+
22+
// Approach 2 : Starting from the End of the Stairs
23+
class Solution {
24+
public:
25+
// Recursive function to calculate the minimum cost to climb stairs starting from index `i`
26+
int solve(vector<int>& cost, int i) {
27+
// Base case: If `i` is 0, the cost is the cost of step 0
28+
if (i == 0) return cost[0];
29+
// Base case: If `i` is 1, the cost is the cost of step 1
30+
if (i == 1) return cost[1];
31+
32+
// Recursive case: Add the cost at the current step and calculate the minimum cost
33+
// of coming from step `i-1` or step `i-2`
34+
return cost[i] + min(solve(cost, i - 1), solve(cost, i - 2));
35+
}
36+
37+
// Function to calculate the minimum cost to reach the top starting from the last or second last step
38+
int minCostClimbingStairs(vector<int>& cost) {
39+
// Start climbing from the last step or the second last step, and take the minimum of the two
40+
return min(solve(cost, cost.size() - 1), solve(cost, cost.size() - 2));
41+
}
42+
};
43+

0 commit comments

Comments
 (0)