(分享) 递归求排列
这代码网络上随处可见,不过我分享的不只是递归,更重要的是分享 分析递归 的方法。/排列、组合、子集都是常见的面试题,我希望能够帮助大家轻松的秒杀那些小菜鸟。
#include <stdio.h>
#include <string.h>
#define NUM 4
#define MAX_DEPTH 2
int mark[NUM+1] = {0};
int printList[NUM+1] = {0};
FILE* Log;
void bgOpenLog(void);
void bgWriteLog(const char* s);
void bgCloseLog(void);
void perm(int depth);
int main(void)
{
bgOpenLog();
perm(1);
bgCloseLog();
getchar();
return 0;
}
void perm(int depth)
{
char s[40] = {0};
int i, j, k;
for (i = 1; i <= NUM; i++)
{
if (!mark[i])
{
for (k = 0; k < depth; k++)
{
bgWriteLog(" ");
}
sprintf(s, "perm: (%d): %d", depth, i);
bgWriteLog(s);
bgWriteLog("\r\n");
mark[i] = 1;
printList[depth] = i;
if (depth < MAX_DEPTH)
{
perm(depth+1);
}
else
{
for (j = 1; j <= MAX_DEPTH; j++)
{
printf("%d ", printList[j]);
}
printf("\n");
}
mark[i] = 0;
}
}
}
void bgOpenLog(void)
{
if(Log == NULL)
Log = fopen("log.txt", "wb");
}
void bgWriteLog(const char* s)
{
fwrite(s, sizeof(char), strlen(s), Log);
}
void bgCloseLog(void)
{
fclose(Log);
Log = NULL;
}
递归调用过程
perm: (1): 1
perm: (2): 2
perm: (2): 3
perm: (2): 4
perm: (1): 2
perm: (2): 1
perm: (2): 3
perm: (2): 4
perm: (1): 3
perm: (2): 1
perm: (2): 2
perm: (2): 4
perm: (1): 4
perm: (2): 1
perm: (2): 2
perm: (2): 3
[ 本帖最后由 BlueGuy 于 2011-1-7 22:50 编辑 ]