Minimum Score Triangulation of Polygon

LeetCode Q 1039 - Minimum Score Triangulation of Polygon

Given N, consider a convex N-sided polygon with vertices labelled A[0], A[i], ..., A[N-1] in clockwise order.
Suppose you triangulate the polygon into N-2 triangles. For each triangle, the value of that triangle is the product of the labels of the vertices, and the total score of the triangulation is the sum of these values over all N-2 triangles in the triangulation.
Return the smallest possible total score that you can achieve with some triangulation of the polygon.

Example 1: Input: [1,2,3] ; Output: 6
Explanation: The polygon is already triangulated, and the score of the only triangle is 6.
Example 2: Input: [3,7,4,5] ; Output: 144
Explanation: 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 is 144.
Example 3: Input: [1,3,1,4,1,5] ; Output: 13
Explanation: The minimum score triangulation has score 1*1*3 + 1*1*4 + 1*1*5 + 1*1*1 = 13.

Note:

  • 3 <= A.length <= 50
  • 1 <= A[i] <= 100

Solution

We use DP to solve this problem.
dp[i][j] denotes the minimum score of Polygon formed from ith node to jth node. Suppose there is a node k between i and j (i < k < j). So the Polygon can be divided into three parts, sub-polygon1 formed by nodes from i to k, sub-polygon2 formed by nodes from k to j and a triangle formed by i, j, k. Then the score of the Polygon is just the sum of three sub-polygons.

Therefore the transfer function is,
dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k][i] + A[i] * A[j] * A[k])

Code: Wrong Version!

public int minScoreTriangulation(int[] A) {
  int n = A.length;
  int[][] dp = new int[n][n];

  for (int i = 0; i < n - 2; i++) {
    for (int j = i + 2; j < n; j++) {
      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][i] + A[i] * A[j] * A[k]);
      }
    }
  }
  
  return dp[0][n - 1];
}

The above code is not correct. Since we need to first get the score of small polygons and then get lager polygons. Suppose we first calculate lager polygons (dp[i][j]), and smaller one (dp[i][k]) has not been calculated, then dp[i][k] = 0. Our reulst dp[i][j] will be wrong. Therefore, we should calculate scores of smallers polygons and then of large polygons, shown as below.

Code: Right Version!

public int minScoreTriangulation(int[] A) {
  int n = A.length;
  int[][] dp = new int[n][n];

  for (int next = 2; next < n; next++) {
    for (int i = 0; i + next < n; i++) {
      j = i + next;
      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][i] + A[i] * A[j] * A[k]);
      }
    }
  }
  
  return dp[0][n - 1];
}

   Reprint policy


《Minimum Score Triangulation of Polygon》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC