-
Notifications
You must be signed in to change notification settings - Fork 242
/
Copy pathMinimumScoreTriangulationOfPolygon.cpp
63 lines (50 loc) · 1.76 KB
/
MinimumScoreTriangulationOfPolygon.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
// https://leetcode.com/problems/minimum-score-triangulation-of-polygon/description/
class Solution {
public:
// Simple Recursive Solution
// int solve(vector<int> &values, int i, int j){
// if(i+1==j)
// return 0;
// int ans= INT_MAX;
// for(int k=i+1; k<j; k++){
// ans= min(ans, values[i]*values[j]*values[k] + solve(values, i, k) + solve(values, k, j));
// }
// return ans;
// }
// Recursion + Memoization (Top-Down Approach)
// int solve(vector<int> &values, int i, int j, vector<vector<int>> &dp){
// if(i+1==j)
// return 0;
// if(dp[i][j]!=-1)
// return dp[i][j];
// int ans= INT_MAX;
// for(int k=i+1; k<j; k++){
// ans= min(ans, values[i]*values[j]*values[k] + solve(values, i, k, dp) + solve(values, k, j, dp));
// }
// dp[i][j]= ans;
// return dp[i][j];
// }
int solve(vector<int> &values){
int n= values.size();
vector<vector<int>> dp(n, vector<int>(n, 0));
for(int i= n-1; i>=0; i--){
for(int j= i+2; j<n; j++){
int ans= INT_MAX;
for(int k=i+1; k<j; k++){
ans= min(ans,values[i]*values[j]*values[k] + dp[i][k] + dp[k][j]);
}
dp[i][j]= ans;
}
}
return dp[0][n-1];
}
int minScoreTriangulation(vector<int>& values) {
// Simple Recursive Solution
// return solve(values, 0, values.size()-1);
// Recursion + Memoization (Top-Down Approach)
// int n= values.size();
// vector<vector<int>> dp(n, vector<int>(n, -1));
// return solve(values, 0, n-1, dp);
return solve(values);
}
};