EXAMPLE
Given an array [1,2,3] or [1,2,3,4] ,print all unique combinations for length 3.
CODE
public class PrintCombo {
public void printCombo(int [] a, int [] buffer, int startIndex, int bufferIndex){
printArray(buffer);
if(buffer.length == bufferIndex){
System.out.println();
System.out.println("SOLUTION START");
printArray(buffer);
System.out.println("SOLUTION END");
System.out.println();
return;
}
if(startIndex == a.length){
return;
}
for(int i = startIndex; i<a.length; i++){
buffer[bufferIndex] = a[i];
printCombo(a,buffer,i+1,bufferIndex+1);
}
}
public void printArray(int [] buffer){
for(int i = 0; i<buffer.length; i++){
System.out.print(" "+buffer[i]);
}
System.out.println();
}
}
OUTPUT
For array [1,2,3] ==> 1,2,3
For array [1,2,3,4] ==> 1,2,3 || 1,2,4 || 1,3,4 || 2,3,4
Problem
I have spent 3 hours tracing the code using a debugger and I am still struggling to understand how the recursive logic is working.
For instance, let's take an example when the array is [1,2,3].
- PrintCombo(a, buffer, 0, 0)
- buffer[0] gets updated to 1
- We call PrintCombo(a, buffer, 1, 1)
- buffer[1] gets updated to 2
- We call PrintCombo(a, buffer, 2, 2)
- buffer[2] gets updated to 3
- We call PrintCombo(a, buffer, 3, 3)
- Since buffer.length == bufferIndex we call printArray.
- We return to the previous call
This is where I get lost. How does the stack make previous calls? I am trying hard to understand this approach thoroughly as I do not like memorizing solutions.
I decided to edit my code by adding a print statement to see what is inside the buffer at every iteration. Here is what I printed for example a = [1,2,3] and buffer size is 3.
0 0 0
1 0 0
1 2 0
1 2 3
SOLUTION START
1 2 3
SOLUTION END
1 3 3
2 3 3
2 3 3
3 3 3