LeetCode 1039. Minimum Score Triangulation of Polygon

原题链接在这里:https://leetcode.com/problems/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:

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

题解:

Edge between A[i] and A[j] would construct only one triangle in polygon. With k between i and j, these 3 nodes construct trangle and the rest i~k, and k~j are polygons. Maintain the minimum.

Let dp[i][j] denotes the minimum score got using nodes from A[i] to A[j].

For all k bigger than i and smaller than j, maintain the mimimum score by min(dp[i][k] + dp[k][j] + A[i]*A[j]*A[k]).

Time Complexity: O(n^3). n = A.length.

Space: O(n^2).

AC Java:

 1 class Solution {
 2     public int minScoreTriangulation(int[] A) {
 3         int n = A.length;
 4         int [][] dp = new int[n][n];
 5         for(int d = 2; d<n; d++){
 6             for(int i = 0; i+d<n; i++){
 7                 int j = i+d;
 8                 dp[i][j] = Integer.MAX_VALUE;
 9                 for(int k = i+1; k<j; k++){
10                     dp[i][j] = Math.min(dp[i][j], dp[i][k]+dp[k][j]+A[i]*A[j]*A[k]);
11                 }
12             }
13         }
14         
15         return dp[0][n-1];
16     }
17 }

Another implementation.

 1 class Solution {
 2     public int minScoreTriangulation(int[] A) {
 3         int n = A.length;
 4         int [][] dp = new int[n][n];
 5         for(int j = 2; j<n; j++){
 6             for(int i = j-2; i>=0; i--){
 7                 dp[i][j] = Integer.MAX_VALUE;
 8                 for(int k = i+1; k<j; k++){
 9                     dp[i][j] = Math.min(dp[i][j], dp[i][k]+dp[k][j]+A[i]*A[j]*A[k]);
10                 }
11             }
12         }
13         
14         return dp[0][n-1];
15     }
16 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/11576043.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值