例子
给定一个数组 [1,2,3] 或者 [1,2,3,4],输出所有长度为 3 的唯一组合。
代码
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();
}
}
输出
对于数组[1,2,3] ==> 1,2,3
对于数组[1,2,3,4] ==> 1,2,3 || 1,2,4 || 1,3,4 || 2,3,4
问题
我花了3个小时用调试器追踪代码,但仍然难以理解递归逻辑是如何工作的。
举个例子,让我们看一个当数组为[1,2,3]的例子。
- PrintCombo(a,buffer,0,0)
- buffer [0]被更新为1
- 我们调用PrintCombo(a,buffer,1,1)
- buffer [1]被更新为2
- 我们调用PrintCombo(a,buffer,2,2)
- buffer [2]被更新为3
- 我们调用PrintCombo(a,buffer,3,3)
- 由于缓冲区长度等于缓冲区索引,因此我们调用printArray。
- 我们返回到上一次调用
这就是我迷失方向的地方。堆栈是如何进行前一个调用的?我正在努力彻底理解这种方法,因为我不喜欢记忆解决方案。
我决定通过添加打印语句来编辑我的代码,以查看每次迭代中缓冲区内部的内容。以下是我为例如a = [1,2,3]和缓冲区大小为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