【问题标题】:Combinations of Unique Subsets of List列表的唯一子集的组合
【发布时间】:2018-06-19 16:13:36
【问题描述】:

鉴于此列表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

【问题讨论】:

  • List(1, 1, 2, 2, 3, 3, 4, 5).toSet.subsets().toList.map(_.toList)
  • 第 2 步呢?我需要弄清楚哪些子集组合构成了我的初始列表。

标签: algorithm scala


【解决方案1】:

试试这个:

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

如果跑得快请回复,否则需要其他方法

【讨论】:

  • val subsets = l.toSet.subsets().toList.map(_.toList).toList.filterNot(x => x == List()) (1 to 2).flatMap(num => subsets.combinations(num).toList.filter(_.flatten.sorted == l.sorted)).toList 有效,但仅适用于较小的 num 组合。只要我这样做(1 to 10),我就会遇到同样的内存问题。
  • 你的预期输出是什么?我猜,答案符合你的标准
  • 请参阅我的问题中的要点 2。我只想要包含初始数组所有元素的集合组合。目前我只考虑具有 2 个不同集合的集合的组合。
  • 您是否编辑过问题?我认为之前的输出有所不同
  • 这个 List(List(1), List(1), List(2), List(2), List(3), List(3), List(4),List( 5)) 独特?请详细说明您需要什么
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-24
  • 2014-12-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多