I was working on the recursive code to print all possible output strings for an input sequence. For simplification I am going to shorten the problem. I have a String[] array. I want to print all possible combinations of words from [0] to [N] considering only one character from a String at a time. Example: String[] a = {"abc", "def", "ghi"} I should be printing adg, adh, adi, aeg.. etc
Here is my recursive code:
void printLetters(String[] list, int count, String result)
{
if(list == null)
return;
if(count > list.length-1)
{
System.out.println(result);
return;
}
for(int i = 0; i<list[count].length(); i++)
{
printLetters(list, count++, result + list[count].charAt(i) + "");
}
}
My code is running into an infinite loop as I am getting a StackOverflowError. Can someone point out my mistake?
The problem is that you are post-incrementing here:
So the recursive call occurs first, then the increment, which practically means you keep calling the method with the same value of
count. Use this instead:And are you sure you want to increment
count? Because when the recursive call returns you will havecount + 1also in the “parent method”, which I don’t think is what you need.