-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1039.minimum-score-triangulation-of-polygon.cpp
105 lines (104 loc) · 2.26 KB
/
1039.minimum-score-triangulation-of-polygon.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
* @lc app=leetcode id=1039 lang=cpp
*
* [1039] Minimum Score Triangulation of Polygon
*
* https://leetcode.com/problems/minimum-score-triangulation-of-polygon/description/
*
* algorithms
* Medium (42.29%)
* Total Accepted: 3.6K
* Total Submissions: 8.6K
* Testcase Example: '[1,2,3]'
*
* 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 {
public:
int n;
int dp[50][50];
int callme(vector<int>& A, int i, int j){
if(j+1 == i)
return 0;
if(j+2 == i){
return A[i]*A[j]*A[j+1];
}
// if(mm.find(i)!=mm.end() && mm[i].find(j)!=mm[i].end())
// return mm[i][j];
if(dp[i][j]!=-1)
return dp[i][j];
int res = INT_MAX;
for(int k = j+1; k!=i; k++){
int tmp = callme(A, k, j) + A[i]*A[k]*A[j] + callme(A, i, k);
res = min(tmp, res);
}
dp[i][j] = res;
return res;
}
int minScoreTriangulation(vector<int>& A) {
n = A.size();
// mm.clear();
for(int i=0; i<50; i++)
for(int j=0; j<50; j++)
dp[i][j] = -1;
return callme(A, n-1, 0);
}
};