You don't really need recursion to do this. Here's an iterative algorithm:
String master = "abcd";
final int L = master.length();
List<String> list = new ArrayList<String>();
list.add(master);
Set<String> current = new HashSet<String>(list);
for (int i = L-1; i >= 2; i--) {
Set<String> next = new HashSet<String>();
for (String s : current) {
for (int k = 0; k < s.length(); k++) {
next.add(s.substring(0, k) + s.substring(k + 1));
}
}
list.addAll(current = next);
}
System.out.println(list);
// prints "[abcd, abc, abd, bcd, acd, ac, ad, ab, bc, bd, cd]"
This is essentially a breadth-first search at heart. You start with a current
set initially containing String master
. Then at each iteration of i
, you go through for (String s : current)
and generate the next
set, which you do by removing every possible character from s
.
Effective Java 2nd Edition: Item 25: Prefer lists to arrays, but if you insist on storing in String[]
, you can just do the following at the end.
String[] arr = list.toArray(new String[0]);
See also