我想获得覆盖矩阵中行的最小元素。
示例输入:
lst = [[1, 2, 3], [2, 3], [3]]
输出:
[3]
另一个示例输入:
lst = [[1], [2, 3], [2, 3]]
输出:
[1, 2], [1, 3]
我试图考虑采用行的组合,但是当我们有大矩阵时,它需要很长时间和大量RAM。
答案 0 :(得分:0)
如同user2357112所说的那样,你可以在维基百科上找到更多关于它的信息: https://en.wikipedia.org/wiki/Set_cover_problem 在这里我建议使用这种增强贪心算法来解决这个问题,并且只有每行中的元素都是唯一的(设置)。
from collections import Counter
matrix = [[1,2,3],[2,3],[2,3]]
minimum =[]
while len(matrix)!=0:
coun = Counter(reduce(lambda x, y: x+y,matrix))
value = coun.most_common()[0][0]
matrix = [s for s in matrix if value not in s]
minimum.append(value)
print minimum
这个解决方案只提供一种解决方案,我认为在大多数情况下这是可接受的近似值。