Skip to content

Commit e89d559

Browse files
authored
Create 01 - Recursive Approach (caused TLE).cpp
1 parent 4ac58fc commit e89d559

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
public:
3+
// Recursive function to calculate the minimum score for triangulating the polygon
4+
// Parameters:
5+
// - v: vector containing the values of the vertices
6+
// - i: starting index of the segment
7+
// - j: ending index of the segment
8+
int solve(vector<int>& v, int i, int j) {
9+
// Base case: If the segment [i, j] has only two vertices, it cannot form a triangle
10+
if (i + 1 == j) return 0;
11+
12+
int ans = INT_MAX; // Initialize the answer to the maximum possible value
13+
14+
// Iterate through all possible middle vertices (k) between i and j
15+
for (int k = i + 1; k < j; k++) {
16+
// Calculate the score of forming a triangle with vertices i, k, and j
17+
// Add the scores of solving the two subproblems [i, k] and [k, j]
18+
ans = min(ans, v[i] * v[k] * v[j] + solve(v, i, k) + solve(v, k, j));
19+
}
20+
21+
return ans; // Return the minimum score for the segment [i, j]
22+
}
23+
24+
// Function to calculate the minimum score triangulation of the polygon
25+
int minScoreTriangulation(vector<int>& values) {
26+
// Call the recursive helper function on the entire polygon
27+
return solve(values, 0, values.size() - 1);
28+
}
29+
};

0 commit comments

Comments
 (0)