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'}
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 clarificati开发者_如何学编程on.
You seem to have used the wrong variable here:
combinations(prefix + array[i], array, index+1);
It should be i
instead of index
:
combinations(prefix + array[i], array, i+1);
Output:
A B C D AB AC AD ABC ABD ABCD ACD BC BD BCD CD
Ideone: http://ideone.com/H4Okw
for (int i = index; i < array.length; i++) {
System.out.println(prefix + array[i]);
combinations(prefix + array[i], array, i + 1);
}
The result is:
A
AB
ABC
AC
B
BC
C
精彩评论