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
思路:一开始着手于 “每个点的分配” 上,如下:
class Solution(object):
def minScoreTriangulation(self, A):
"""
:type A: List[int]
:rtype: int
"""
memo = {}
def helper(a):
if len(a)==3: return a[0]*a[1]*a[2]
if tuple(a) in memo: return memo[tuple(a)]
if tuple(a[::-1]) in memo: return memo[tuple(a[::-1])]
res = float('inf')
for i in range(2,len(a)-1):
tmp = helper(a[:i+1]) + helper(a[i:]+[a[0]])
res = min(res, tmp)
tmp = helper(a[:2]+[a[-1]]) + helper(a[1:])
res = min(res, tmp)
memo[tuple(a)] = memo[tuple(a[::-1])] = res
return res
return helper(A)
上述方法会TLE,数组转tuple耗时较多,想用(start,end)的方式表示key,但是无从下手,因为多边形是封闭的,首尾corner是连在一起的。
换一个思路是考虑相邻2个点,也就是一条边,而且这条边就是“首尾相连的边”,这样就不需要在key里面表示“首尾corner” 相连的case了,即每次在求dp[s][t]的时候就已经考虑完了“首尾相连的边”的归属,如果每次求dp[s][t]不是考虑的首尾边,就无法用一个2元组作为key
class Solution(object):
def minScoreTriangulation(self, A):
"""
:type A: List[int]
:rtype: int
"""
memo = {}
def helper(a, s, t):
if t-s+1<3: return 0
if t-s+1==3: return a[s]*a[s+1]*a[s+2]
if (s,t) in memo: return memo[(s,t)]
res = float('inf')
for i in range(s+1,t):
tmp = a[s]*a[t]*a[i]
tmp += helper(a,s,i)
tmp += helper(a,i,t)
res = min(res, tmp)
memo[(s,t)] = res
return res
return helper(A, 0, len(A)-1)
s=Solution()
print(s.minScoreTriangulation([1,2,3]))
print(s.minScoreTriangulation([32,43,74,29,64,98,96,19,20,33,19,7,9,98,63,6,65,31,13,97]))
print(s.minScoreTriangulation([3,7,4,5]))
print(s.minScoreTriangulation([1,3,1,4,1,5]))