In my application, I need all subsets of a given size k of an array 1..n.
This could easily be done using a recursive approach and storing all found subsets along the way. However, I don't want my application to use an exponential amount of memory [O(n^k)].
Therefore, I want to write a class that implements (Java's) Iterator
to iterate over said subsets.
public class SubsetIterator implements Iterator<int[]> {
private int k;
private int[] array;
public SubsetIterator(int k, int[] array) {
this.k = k;
this.array = array;
}
@Override
public boolean hasNext() {
//To be implemented.
}
@Override
public int[] next() {
//To be implemented.
}
}
So I can use it as follows:
SubsetIterator iter = new SubsetIterator(k, array);
while (iter.hasNext) {
int[] next = iter.next();
//Do stuff
}
Obviously we will need to store the current subset last returned by next()
which is initialized as 1..k. But how could one compute the next subset from this current subset?