algorithm - 列表的唯一子集的组合

标签 algorithm scala

给定此列表 List(1, 1, 2, 2, 3, 3, 4, 5),我如何生成列表子集的所有组合,具有以下约束:

  1. 每个子集只能包含唯一元素。
  2. 子集的每个组合必须包含初始列表中的所有元素(包括重复元素)。展平组合应该等于我的初始列表。

以下是一些可能的组合:

List(List(1), List(1), List(2), List(2), List(3), List(3), 
List(4),List(5)) // 1*8
List(List(1,2), List(1,2), List(3,4), List(3,5)) // 2 *4
List(List(1,2,3), List(1,2,3), List(4,5)) // 3,3 and 2
List(List(1,2,3,4), List(1,2,3,5)) // 4 and 4
List(List(1,2,3,4,5), List(1,2,3)) // 5 and 3

我试过这样的:

val myList = List(1, 1, 2, 2, 3, 3, 4, 5)

val combs = (1 to 5).map(n => myList.combinations(n).toList.filter(x => x.distinct sameElements x)).toList.flatten

val step2 = (1 to combs.length).flatMap(n => combs.combinations(n)).toList

但是计算成本太高了:

java.lang.OutOfMemoryError: Java heap space

最佳答案

试试这个:

val listLen = l.toSet.size
(1 to listLen).flatMap(x => l.combinations(x).map(x => x.distinct))

如果运行速度快请回复,否则需要走其他途径

关于algorithm - 列表的唯一子集的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50880557/

相关文章:

r - k-均值聚类与新的训练数据?

scala - 在 Spark 作业中写入 HBase : a conundrum with existential types

algorithm - 在 Scala 中更新节点的值?

string - Scala 运行时字符串插值/格式化

scala - List[OptionT[Future, Int]] 到 OptionT[Future, List[A]]

python - 为什么这个线性分类器算法是错误的?

c++ - 为什么尽管具有相同的算法和数据结构,但另一个解决方案的效率却提高了 10 倍?

algorithm - 计算 1/d 的快速算法?(SRT,goldsmidt,newton raphson,...)

algorithm - 矢量删除给出意想不到的结果

scala - 幺半群同态和同构