Cover image for LeetCode Daily Problem P1039: Minimum Score of Polygon Triangulation

LeetCode Daily Problem P1039: Minimum Score of Polygon Triangulation


Timeline

Timeline

2025-09-29

init

Dynamic Programming

Problem:

This problem clearly has subproblems and can be approached with dynamic programming. Assume vertices from i to k, with k between i and j but not equal to i or j. Then the problem equals the minimum triangulation score from i to k plus the minimum triangulation score from k to j plus the area of the triangle formed by i, j, k. Because no matter how you partition, i and j must form a triangle with some vertex in between. Thus we can write the state transition equation:

dp[i][j]=min(dp[i][k]+dp[k][j]+values[i]values[j]values[k])dp[i][j] =min( dp[i][k] + dp[k][j] + values[i] *values[j] *values[k])

dp[i][j] represents the minimum triangulation score of the convex polygon from vertex i to vertex j, where k is any vertex between i and j excluding i and j

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <climits>
#include <vector>
using std::vector;

class Solution {
public:
// dp[i][j]: minimum triangulation score of the convex polygon from vertex i to vertex j
// k is any vertex between i and j excluding i and j
// dp[i][j] =min k{ dp[i][k] + dp[k][j]+ values[i] *values[j] *values[k]}
int minScoreTriangulation(vector<int> &values)
{
int vertex; // How many vertices are there from i to j?
int i, j, k;
int n;

n = values.size();

vector<vector<int> > dp(n, vector<int>(n, 0));

for (vertex = 2; vertex < n; vertex++) {
for (i = 0; i + vertex < n; i++) {
j = i + vertex;
dp[i][j] = INT_MAX;
for (k = i + 1; k < j; k++) {
dp[i][j] =
std::min(dp[i][j],
dp[i][k] + dp[k][j] +
values[i] * values[j] * values[k]);
}
}
}
return dp[0][n - 1];
}
};