递归是我遇到麻烦的一件事。对于这项任务,我们应该打印出部分和子部分的轮廓。以下面的例子为例。
Section 1
Section 1.A
Section 1.A.1
Section 1.A.2
Section 1.B
Section 1.B.1
Section 1.B.2
Section 2
Section 2.A
Section 2.A.1
Section 2.A.2
Section 2.B
Section 2.B.1
Section 2.B.2
此示例的深度为3,高度为2.
到目前为止,这是我的代码,它不会接近正确的输出。
void printDepth(int depth, int width, int minusDepth, int minusWidth) {
int i = 0;
if(depth == 0)
printf("Section XX\n");
else {
printf("\t");
printDepth(depth -1, width, minusDepth, minusWidth);
}
}
这是来自main()
的电话int minusDepth = 0;
int minusWidth = 0;
printDepth(depth, width, minusDepth, minusWidth);
但是,对于深度= 4和宽度= 5,这只打印出来:
\ t \ t \ t \ t第XX节
我真的不确定如何继续。递归是我存在的祸根。
答案 0 :(得分:3)
#include <stdio.h>
void printDepth(int deep, int depth, int height, char *table) {
if(deep == depth)
return ;
int i, j;
char bak = table[deep];
for(i = 0; i < height; ++i){
printf("%*s%s", deep*2, "", "Section ");
for(j = 0; j <= deep; ++j){
if(j)
putchar('.');
putchar(table[j]);
}
putchar('\n');
printDepth(deep+1, depth, height, table);
table[deep]++;
}
table[deep] = bak;//restore
}
int main(void){
char table[] = "1A1";//Effective range up to 1-9 and A-Z
printDepth(0, 3, 2, table);
return 0;
}
答案 1 :(得分:3)
你需要一个循环来打印当前深度的部分并执行height
(我称之为width
)递归。您还需要传递一个包含节字符串当前前缀的字符串。
#include <stdio.h>
#include <assert.h>
#include <math.h>
#define MAX_DEPTH 100
#define MAX_WIDTH 99 // NOTE: if you increase this then section's decl in printDepth needs to be updated too
void printDepth_r(int currDepth, int depth, int width, char *section, char *sub)
{
if (currDepth == depth) // recursion base case
return;
for (int i = 0; i < width; ++i)
{
// TODO: write to sub the subsection determined by (currDepth, width)
fprintf(stdout, "%*sSection %s\n", currDepth * 2, "", section);
// TODO: append "." to sub for descendant recursions
printDepth_r(currDepth + 1, depth, width, section, sub + /* TODO: num chars written to sub */);
}
}
int printDepth(int depth, int width)
{
char section[MAX_DEPTH * (2 + 1) + 1]; // NOTE: 2 == 1 + (int) (log(99) / log(10));
assert(sizeof(section) >= MAX_DEPTH * (1 + (int) (log(MAX_WIDTH) / log(10)) + 1) + 1);
if (depth > MAX_DEPTH || width > MAX_WIDTH)
return -1;
printDepth_r(0, depth, width, section, section);
return 0;
}
int main(int argc, char **argv)
{
printDepth(3, 2);
return 0;
}
请注意,我们会将depth
,width
和section
的相同值传递给所有递归。因此,如果我们想减少递归在每个级别上的堆栈空间量,那么我们可以将它们拉出到一个结构中,并将1个结构指针传递给这3个常量。或者,更好的是,我们可以将这些值存储在线程本地存储中。无论哪种方式都可以在溢出堆栈之前允许更深的递归。