题目链接:
枚举
枚举所有的三角形,然后计算三角形的面积并找出最大的三角形面积。设三角形三个顶点的坐标为 ( x 1 , y 1 ) (x_1, y_1) (x1,y1) ( x 2 , y 2 ) (x_2, y_2) (x2,y2)和 ( x 3 , y 3 ) (x_3, y_3) (x3,y3),则三角形面积 S S S 可以用行列式的绝对值表示:
S = 1 2 ∥ x 1 y 1 1 x 2 y 2 1 x 3 y 3 1 ∥ = 1 2 ∣ x 1 y 2 + x 2 y 3 + x 3 y 1 − x 1 y 3 − x 2 y 1 − x 3 y 2 ∣ S=\frac{1}{2} \begin{Vmatrix} x_1&y_1&1\\ x_2&y_2&1\\ x_3&y_3&1\\ \end{Vmatrix}=\frac{1}{2}|x_1y_2+x_2y_3+x_3y_1-x_1y_3-x_2y_1-x_3y_2| S=21 x1x2x3y1y2y3111 =21∣x1y2+x2y3+x3y1−x1y3−x2y1−x3y2∣
class Solution {
public:
double triangleArea(int x1, int y1, int x2, int y2, int x3, int y3) {
return 0.5 * abs(x1 * y2 + x2 * y3 + x3 * y1 - x1 * y3 - x2 * y1 - x3 * y2);
}
double largestTriangleArea(vector<vector<int>> & points) {
int n = points.size();
double ret = 0.0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
for (int k = j + 1; k < n; k++) {
ret = max(ret, triangleArea(points[i][0], points[i][1], points[j][0], points[j][1], points[k][0], points[k][1]));
}
}
}
return ret;
}
};