-3

I need to generate a list of all distinct combinations for a given group of integers in java.

Example here:

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

So a list of 1,2,3 would give me

[], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]
Alexis C.
  • 91,686
  • 21
  • 171
  • 177
joeborg
  • 11
  • 2

1 Answers1

1

what you are trying to implements its the power set, thats means the set of all subsets of a group, including the empty set and the group itself.

Here is one possible iterative implementation in 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;
}
AmerNasser
  • 33
  • 1
  • 7