File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
24 - Dynamic Programming Problems/16 - Minimum Score Triangulation of Polygon Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ // Function to calculate the minimum score triangulation of the polygon using bottom-up DP
4+ int solve (vector<int >& v) {
5+ int n = v.size (); // Number of vertices in the polygon
6+
7+ // DP table where dp[i][j] represents the minimum score for triangulating the segment [i, j]
8+ vector<vector<int >> dp (n, vector<int >(n, 0 ));
9+
10+ // Iterate over all possible starting indices in reverse (bottom-up DP)
11+ for (int i = n - 1 ; i >= 0 ; i--) {
12+ // Iterate over all possible ending indices for segments larger than 2 vertices
13+ for (int j = i + 2 ; j < n; j++) {
14+ int ans = INT_MAX; // Initialize the minimum score for the segment [i, j]
15+
16+ // Try every possible middle vertex k between i and j
17+ for (int k = i + 1 ; k < j; k++) {
18+ // Calculate the score of forming a triangle (i, k, j) and add subproblem scores
19+ ans = min (ans, v[i] * v[j] * v[k] + dp[i][k] + dp[k][j]);
20+ }
21+
22+ // Store the minimum score for the segment [i, j]
23+ dp[i][j] = ans;
24+ }
25+ }
26+
27+ // The final result is stored in dp[0][n-1], which represents the entire polygon
28+ return dp[0 ][n - 1 ];
29+ }
30+
31+ // Main function to calculate the minimum score triangulation
32+ int minScoreTriangulation (vector<int >& values) {
33+ int n = values.size (); // Number of vertices in the polygon
34+
35+ // Call the DP function
36+ return solve (values);
37+ }
38+ };
You can’t perform that action at this time.
0 commit comments