You have a convex n-sided polygon where each vertex has an integer value. You are given an integer array values where values[i] is the value of the ith vertex in clockwise order.
Polygontriangulation is a process where you divide a polygon into a set of triangles and the vertices of each triangle must also be vertices of the original polygon. Note that no other shapes other than triangles are allowed in the division. This process will result in n - 2 triangles.
You will triangulate the polygon. For each triangle, the weight of that triangle is the product of the values at its vertices. The total score of the triangulation is the sum of these weights over all n - 2 triangles.
Return the minimum possible score that you can achieve with some triangulation of the polygon.
Input: values =[3,7,4,5]Output: 144Explanation: There are two triangulations,with possible scores:3*7*5+4*5*7=245, or 3*4*5+3*4*7=144.The minimum score is144.
We can break the polygon into smaller sub-polygons and solve for each interval. The minimum triangulation for an interval is the minimum over all possible ways to split it by choosing a third vertex.
classSolution {
public:int minScoreTriangulation(vector<int>& values) {
int n = values.size();
vector<vector<int>> dp(n, vector<int>(n));
for (int l =3; l <= n; ++l) {
for (int i =0; i + l <= n; ++i) {
int j = i + l -1;
dp[i][j] = INT_MAX;
for (int k = i +1; k < j; ++k)
dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j] + values[i]*values[j]*values[k]);
}
}
return dp[0][n-1];
}
};
classSolution {
publicintminScoreTriangulation(int[] values) {
int n = values.length;
int[][] dp =newint[n][n];
for (int l = 3; l <= n; ++l) {
for (int i = 0; i + l <= n; ++i) {
int j = i + l - 1;
dp[i][j]= Integer.MAX_VALUE;
for (int k = i + 1; k < j; ++k)
dp[i][j]= Math.min(dp[i][j], dp[i][k]+ dp[k][j]+ values[i]*values[j]*values[k]);
}
}
return dp[0][n-1];
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
funminScoreTriangulation(values: IntArray): Int {
val n = values.size
val dp = Array(n) { IntArray(n) }
for (l in3..n) {
for (i in0..n-l) {
val j = i + l - 1 dp[i][j] = Int.MAX_VALUE
for (k in i+1 until j)
dp[i][j] = minOf(dp[i][j], dp[i][k] + dp[k][j] + values[i]*values[j]*values[k])
}
}
return dp[0][n-1]
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defminScoreTriangulation(self, values: list[int]) -> int:
n = len(values)
dp = [[0]*n for _ in range(n)]
for l in range(3, n+1):
for i in range(n-l+1):
j = i + l -1 dp[i][j] = float('inf')
for k in range(i+1, j):
dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j] + values[i]*values[j]*values[k])
return dp[0][n-1]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
impl Solution {
pubfnmin_score_triangulation(values: Vec<i32>) -> i32 {
let n = values.len();
letmut dp =vec![vec![0; n]; n];
for l in3..=n {
for i in0..=n-l {
let j = i + l -1;
dp[i][j] =i32::MAX;
for k in i+1..j {
dp[i][j] = dp[i][j].min(dp[i][k] + dp[k][j] + values[i]*values[j]*values[k]);
}
}
}
dp[0][n-1]
}
}