原题说明
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: 375 + 457 = 245, or 345 + 347 = 144. The minimum score is 144.
Example 3:
Input: [1,3,1,4,1,5]
Output: 13
Explanation: The minimum score triangulation has score 113 + 114 + 115 + 111 = 13.
Note:
3 <= A.length <= 50
1 <= A[i] <= 100
解题思路
动态规划,递归可以使逻辑简单(本质还是动态规划)
- 将多边形起始位置设为
start
,end
, 用一个数组dp来记录任意起始位置的score
- 为了计算
dp[start][end]
, 我们用一个indexk
在start
到end
之间遍历dp[start][end] = min(dp[start][k] + dp[k][end] + A[start] * A[k] * A[end])
- 结果为
dp[0][n - 1]
注意: - 相邻的
dp[i][i + 1] = 0
, 因为两条边无法组成三角形 - 如果用传统动归的方法,必须
i
的位置从j
开始往前推,不能i
和j
都从小往大推,不然dp[k][j]
是未知的。
示例代码 (cpp)
递归(实际上还是动态规划,因为有memorization)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23class Solution {
int getScore(const vector<int>& A, vector<vector<int>>& dp, int start, int end) {
if (start >= end - 1) {
return 0;
}
if (dp[start][end] > 0) {
return dp[start][end];
}
int score = INT_MAX;
for (int k = start + 1; k <= end - 1; ++k) {
score = min(score, getScore(A, dp, start, k) + getScore(A, dp, k, end) + A[start] * A[k] * A[end]);
}
dp[start][end] = score;
return score;
}
public:
// 递归(实际上还是动态规划,因为有memorization)
int minScoreTriangulation(vector<int>& A) {
int n = A.size();
vector<vector<int>> dp(n, vector<int>(n, 0));
return getScore(A, dp, 0, n - 1);
}
};
动态规划1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16class Solution {
public:
int minScoreTriangulation(vector<int>& A) {
int n = A.size();
vector<vector<int>> dp(n, vector<int>(n, 0));
for (int j = 2; j < n; ++j) {
for (int i = j - 2; i >= 0; --i) {
dp[i][j] = INT_MAX;
for (int k = i + 1; k < j; ++k) {
dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j] + A[i] * A[j] * A[k]);
}
}
}
return dp[0][n - 1];
}
};
示例代码 (java)
1 | class Solution { |
示例代码 (python)
1 | class Solution: |
复杂度分析
时间复杂度:O(N^3)
, 用传统动归可以很容易看出,用递归的方法可以想到任意dp[i][j]
都遍历一次O(N^2)
,而每一次遍历中
都有一个 for (int k = start + 1; k <= end - 1; ++k)
用到O(N)
空间复杂度:O(N^2)
, 递归会使用额外的O(N)
stack
归纳总结
我们在Youtube上更新了视频讲解,欢迎关注!