lc 1039. minimum score triangulation of polygon.md

Description

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.

1
2
3
Input: [1,2,3]
Output: 6
Explanation: The polygon is already triangulated, and the score of the only triangle is 6.

Solution

1
2
We can use dp to solve this problem, dp[i][j] means the result from i to j, therefore, we should get dp[0][n - 1].
The function is very easy to understand.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class :
def minScoreTriangulation(self, A: List[int]) -> int:

cache = {}
def dp(i, j):
if (i, j) not in cache:
cache[i, j] = min([dp(i, k) + dp(k, j) + A[i] * A[j] * A[k] for k in range(i + 1, j)] or [0])
return cache[i, j]
return dp(0, len(A) - 1)

# top down solution
n = len(A)
dp = [[0] * n for _ in range(n)]
for d in range(2, n):
for i in range(n - d):
j = i + d
dp[i][j] = min(dp[i][k] + dp[k][j] + A[i] * A[j] * A[k] for k in range(i + 1, j))
return dp[0][n - 1]