Skip to content

Commit a0e80ab

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

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
class Solution {
2+
public:
3+
// Recursive function with memoization 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+
// - dp: 2D vector to store previously computed results for subproblems
9+
int solve(vector<int>& v, int i, int j, vector<vector<int>>& dp) {
10+
// Base case: If the segment [i, j] has only two vertices, it cannot form a triangle
11+
if (i + 1 == j) return 0;
12+
13+
// If the result for this subproblem is already computed, return it
14+
if (dp[i][j] != -1) return dp[i][j];
15+
16+
int ans = INT_MAX; // Initialize the answer to the maximum possible value
17+
18+
// Iterate through all possible middle vertices (k) between i and j
19+
for (int k = i + 1; k < j; k++) {
20+
// Calculate the score of forming a triangle with vertices i, k, and j
21+
// Add the scores of solving the two subproblems [i, k] and [k, j]
22+
ans = min(ans, v[i] * v[k] * v[j] + solve(v, i, k, dp) + solve(v, k, j, dp));
23+
}
24+
25+
// Store the computed result for the segment [i, j] in the dp table
26+
return dp[i][j] = ans;
27+
}
28+
29+
// Function to calculate the minimum score triangulation of the polygon
30+
int minScoreTriangulation(vector<int>& values) {
31+
int n = values.size(); // Number of vertices in the polygon
32+
33+
// Initialize a dp table with -1 to indicate uncomputed results
34+
vector<vector<int>> dp(n + 1, vector<int>(n + 1, -1));
35+
36+
// Call the recursive helper function on the entire polygon
37+
return solve(values, 0, n - 1, dp);
38+
}
39+
};

0 commit comments

Comments
 (0)