【问题标题】:Java Combinations of list of int [duplicate]int列表的Java组合[重复]
【发布时间】:2014-05-16 13:39:08
【问题描述】:

我需要为 java 中给定的一组整数生成所有不同组合的列表。

此处示例:

https://www.wolframalpha.com/input/?i=combinations+of+%7B1%2C2%2C3%7D

所以1,2,3 的列表会给我

[], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]

【问题讨论】:

  • 这是一个非常适合自己做的练习。
  • 关于这个问题,SO上有很多类似的问题。

标签: java list int combinations


【解决方案1】:

你试图实现它的幂集,这意味着一个组的所有子集的集合,包括空集和组本身。

以下是 java 中一种可能的迭代实现:

public static <T> List<List<T>> powerset(Collection<T> list) {
List<List<T>> ps = new ArrayList<List<T>>();
ps.add(new ArrayList<T>());   // add the empty set

// for every item in the original list
for (T item : list) {
List<List<T>> newPs = new ArrayList<List<T>>();

for (List<T> subset : ps) {
  // copy all of the current powerset's subsets
  newPs.add(subset);

  // plus the subsets appended with the current item
  List<T> newSubset = new ArrayList<T>(subset);
  newSubset.add(item);
  newPs.add(newSubset);
}

// powerset is now powerset of list.subList(0, list.indexOf(item)+1)
ps = newPs;
}
return ps;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-02
    • 2020-08-01
    • 2016-11-05
    • 1970-01-01
    • 2018-11-03
    相关资源
    最近更新 更多