I have the following recursion that is supposed to give all the combinations of a given String. For example, the String "XYZ" should give the combinations: XYZ, XY, XZ, YZ, X,Y,Z. More specifically, the number of combinations should be (2^n)-1. Hence, for the String "XYZ", we have (2^3)-1. My recursive method is working absolutely fine for n=1, n=2.
For n=3, my recursive method outputs a duplicate letter but it does contain (2^3)-1 = 7 distinct combinations.
For n=4, my recursive method outputs 5 duplicate elements and 14 distinct elements( instead of (2^4)-1 = 15 elements)
For n=5, my recursive method outputs 17 duplicate elements and 25 distinct elements( instead of (2^5)-1 = 31 elements)
public static void Generate(String word)
{
if(word.length() == 1)
System.out.println(word);
else { // if the word is at least 2 characters
for(int i=1; i<word.length(); i++)
{
System.out.println(word.substring(0,1) + word.substring(i));
}
Generate(word.substring(1)); // this line will remove the first character
Generate(word.substring(0,word.length()-1)); // this line will remove the last character
}
}
The output for XYZ is:
XYZ, XZ, YZ, Z, Y, XY,
Y, X,
and the output for WXYZ is:
WXYZ, WYZ, WZ, XYZ, XZ, YZ, Z, Y, XY,
Y, X, WXY, WY,
XY,
Y,
X, WX,
X, W,
Note here that there are 14 combinations instead of 15. Why is the "WXZ" combination is missing??
The elements that are in bold are duplicate elements.
Can someone please tell me what is wrong in my recursive method and help me to make it work for n>4. I believe that it works fine from n=1 to n=3 because suppose that I put the elements in a Set, the duplicate elements will be removed. But for n=4, as you can see, there is a combination missing and I fail to understand why. Please help me out... Thanks a lot for your help. I am quite sure that it is something really small but because I have been working on this recursion from non-stop hours, I just can't see it...