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] 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
#include<climits> #include<vector> using std::vector;
classSolution { 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]} intminScoreTriangulation(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]; } };