How do you write a recursive method PowerSet(String input) that prints out all possible combinations of a string that is passed to it?
For example: PowerSet(\"abc\")
Well if you don't have loops, emulate one with recursion, using iterators this is acutally quite simple.
public final Set> powerSet(Set set) {
Set> powerSet = new HashSet<>();
powerSet(set, powerSet, set.iterator());
return powerSet;
}
public final void powerSet(Set set, Set> powerSet, Iterator iterator) {
if(iterator.hasNext()) {
Integer exlude = iterator.next();
Set powThis = new HashSet();
powThis.addAll(set);
powThis.remove(exlude);
powerSet.add(powThis);
powerSet(powThis, powerSet, powThis.iterator());
powerSet(set, powerSet, iterator);
}
}
//usage
Set set = new HashSet<>();
set.add(1);
set.add(2);
set.add(3);
set.add(4);
log.error(powerSet(set).toString());