題目
給定包含多個點的集合,從其中取三個點組成三角形,返回能組成的最大三角形的面積。
示例:
輸入: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]
輸出: 2
解釋:
這五個點如下圖所示。組成的橙色三角形是最大的,面積爲2。
注意:
3 <= points.length <= 50.
不存在重複的點。
-50 <= points[i][j] <= 50.
結果誤差值在 10^-6 以內都認爲是正確答案。
求面積:鞋帶公式
解答
class Solution(object):
def largestTriangleArea(self, points):
def area(p, q, r):
return .5 * abs(p[0]*q[1]+q[0]*r[1]+r[0]*p[1]
-p[1]*q[0]-q[1]*r[0]-r[1]*p[0])
return max(area(*triangle)
for triangle in itertools.combinations(points, 3))
複雜度分析
時間複雜度:O(N^3),其中 N 是數組 points 的長度。
空間複雜度:O(1)。
就是這麼暴力
這裏用到了Python itertools模塊combinations方法
1、Python itertools模塊combinations(iterable, r)方法可以創建一個迭代器,返回iterable中所有長度爲r的子序列,返回的子序列中的項按輸入iterable中的順序排序。
import itertools
list1 = [1, 3, 4, 5]
list2 = list(itertools.combinations(list1, 2))
print(list2)
返回結果:
[(1, 3), (1, 4), (1, 5), (3, 4), (3, 5), (4, 5)]
2、實現一組數據的所有排列組合
import itertools
list1 = [1, 3, 4, 5]
list2 = []
for i in range(1, len(list1)+1):
iter1 = itertools.combinations(list1, i)
list2.append(list(iter1))
print(list2)
返回結果:
[[(1,), (3,), (4,), (5,)], [(1, 3), (1, 4), (1, 5), (3, 4), (3, 5), (4, 5)], [(1, 3, 4), (1, 3, 5), (1, 4, 5), (3, 4, 5)], [(1, 3, 4, 5)]]