调用堆栈:
rec(pool, 0, 3);
-> 'l' rec(pool, 1, 3);
-> 'q' rec(pool, 2, 3);
-> 'a' rec(pool, 3, 3);
-> '\n'
-> 'e' rec(pool, 3, 3);
-> '\n'
-> 'i' rec(pool, 3, 3);
-> '\n'
-> ...
-> ...
-> ...
更新:
不像递归。但是..它有效:)。希望这可以帮助。
假设最大长度为 10。
#include <stdio.h>
#include <string.h>
#define ALL_DONE 1
#define NOT_YET 0
int rec(char (*pool)[10], int num, int start);
int main(void)
{
int i, num;
char pool[20][10];
scanf("%d", &num);
for (i = 0; i < num; i++){
scanf("%s", pool[i]);
}
while ( !rec(pool, num, 0) ); // keepint calling until all permutations are printed
return 0;
}
int rec(char (*pool)[10], int num, int start)
{
static int ndx[20] = {0}; // record the index of each string
if (start == num){
printf("\n");
return ALL_DONE;
}
printf("%c", pool[start][ndx[start]]);
if ( rec(pool, num, start+1) == ALL_DONE ){
ndx[start+1] = 0;
ndx[start]++;
if (ndx[start] == strlen(pool[start])){
return ALL_DONE;
return NOT_YET;
}
return NOT_YET;
}
解释:
rec(pool, 0, 0)[1st calling]
-> 'l' rec(pool, 1, 0) | ndx[0..2] = 0, 0, 0
-> 'q' rec(pool, 2, 0) | ndx[0..2] = 0, 0, 0
-> 'a' rec(pool, 3, 0) | ndx[0..2] = 0, 0, 0
-> '\n' retrun ALL_DONE | ndx[0..2] = 0, 0, 0
-> return NOT_YET | ndx[0..2] = 0, 0, 1
-> return NOT_YET | ndx[0..2] = 0, 0, 1
-> return NOT_YET | ndx[0..2] = 0, 0, 1
|
rec(pool, 0, 0)[2nd]
-> 'l' rec(pool, 1, 0) | ndx[0..2] = 0, 0, 1
-> 'q' rec(pool, 2, 0) | ndx[0..2] = 0, 0, 1
-> 'e' rec(pool, 3, 0) | ndx[0..2] = 0, 0, 1
-> '\n' return ALL_DONE | ndx[0..2] = 0, 0, 1
-> return NOT_YET | ndx[0..2] = 0, 0, 2
-> return NOT_YET | ndx[0..2] = 0, 0, 2
-> return NOT_YET | ndx[0..2] = 0, 0, 2
|
| ...
|
rec(pool, 0, 0)[4th]
-> 'l' rec(pool, 1, 0) | ndx[0..2] = 0, 0, 3
-> 'q' rec(pool, 2, 0) | ndx[0..2] = 0, 0, 3
-> 'o' rec(pool, 3, 0) | ndx[0..2] = 0, 0, 3
-> '\n' return ALL_DONE | ndx[0..2] = 0, 0, 3
-> return ALL_DONE | ndx[0..2] = 0, 0, 4
-> return NOT_YET | ndx[0..2] = 0, 1, 0
-> return NOT_YET | ndx[0..2] = 0, 1, 0
|
| ...
| ...
|
rec(pool, 0, 0)[5th]
-> 'l' rec(pool, 1, 0) | ndx[0..2] = 0, 1, 0
-> 'r' rec(pool, 2, 0) | ndx[0..2] = 0, 1, 0
-> 'a' rec(pool, 3, 0) | ndx[0..2] = 0, 1, 0
-> '\n' return ALL_DONE | ndx[0..2] = 0, 1, 0
-> return NOT_YET | ndx[0..2] = 0, 1, 1
-> return NOT_YET | ndx[0..2] = 0, 1, 1
-> return NOT_YET | ndx[0..2] = 0, 1, 1
|
| ...
|
rec(pool, 0, 0)[8th]
-> 'l' rec(pool, 1, 0) | ndx[0..2] = 0, 1, 3
-> 'r' rec(pool, 2, 0) | ndx[0..2] = 0, 1, 3
-> 'o' rec(pool, 3, 0) | ndx[0..2] = 0, 1, 3
-> '\n' return ALL_DONE | ndx[0..2] = 0, 1, 3
-> return ALL_DONE | ndx[0..2] = 0, 1, 4
-> return ALL_DONE | ndx[0..2] = 0, 2, 0
-> return ALL_DONE | ndx[0..2] = 1, 0, 0
|
| FINISH