我想避免使用嵌套的for循环,因为它应该由用户给定的整数递归地增加深度。
因此,如果用户输入3,它应该像下面的例子一样嵌套..如果用户输入6,那里应该还有三个循环!?
#include <stdio.h>
int main(void)
{
// int depth_lvl = 3
char n[] = {'a','b','c'};
int i,j,y;
int x = sizeof(n);
for(i = 0; i < x; i++)// <---- LEVEL 1
{
printf("%c\n",n[i]);
for(j = 0; j < x; j++)// <---- LEVEL 2
{
printf("%c%c\n",n[i],n[j]);
for(y = 0; y < x; y++) // <---- LEVEL 3
{
printf("%c%c%c\n",n[i],n[j],n[y]);
}
}
}
}
答案 0 :(得分:1)
这是你想要的吗? 该解决方案使用递归和每个级别的中间结果字符串,使用该字符串将当前级别的每个状态转移到下一个更深层次。
#define MAX_DEPTH 6
void printRecursive(char n[], int x, int curDepth, char* result)
{
// note: x is supposed to be sizeof(n).
if (x > MAX_DEPTH) // prohibit overflow of intermediateResult
x = MAX_DEPTH;
if (curDepth < x) {
char intermediateResult[MAX_DEPTH+1];
if (result)
strcpy(intermediateResult,result);
else
strcpy(intermediateResult, "");
for (int i=0;i<x;i++) {
intermediateResult[curDepth] = n[i];
intermediateResult[curDepth+1] = '\0';
printRecursive(n,x,curDepth+1,intermediateResult);
}
}
if (curDepth > 0)
printf("%s\n", result);
}
int main(void)
{
char n[] = {'a','b','c', 'd'};
int x = sizeof(n);
printRecursive(n, x, 0, NULL);
return 0;
}