给定此列表 List(1, 1, 2, 2, 3, 3, 4, 5)
,我如何生成列表子集的所有组合,具有以下约束:
- 每个子集只能包含唯一元素。
- 子集的每个组合必须包含初始列表中的所有元素(包括重复元素)。展平组合应该等于我的初始列表。
以下是一些可能的组合:
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/