I have a recursion project to find all the sequences(or subsets) of a Char array as such that each character appears in the same order. For Example, for the array Char[] letters = {'A', 'B','C','D'}
The one letter sequences are "A","B","C,"D".
Two letter sequences are "AB","AC","AD","BC","BD","CD".
Three letter sequences are "ABC", "ABD","ACD","BCD"
Four letter sequence is "ABCD"
Now I thought I was on the right track with the code below, but I'm getting a lot of duplicates. I'm getting really frustrated. If anyone can point me in the right direction, I would appreciate it.
// print all subsets of the characters in s
public static void combinations(char[] array) { combinations("", array, 0); }
// print all subsets of the remaining elements, with given prefix
private static void combinations(String prefix, char[] array, int index) {
for(int i = index; i < array.length; i++)
{
System.out.println(prefix + array[i]);
}
if (index < array.length) {
for(int i = index; i < array.length; i++){
combinations(prefix + array[i], array, index+1);
}
}
}
Editting out my edit for clarification.
ifstatement seems redundant. The same check is already present in theforloop condition.