递归是我遇到很多麻烦的一件事。对于此作业,我们应该打印出部分和子部分的大纲。以下面为例。
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);
但是,对于 depth = 4 和 width = 5,这只会打印出:
\t\t\t\t第 XX 节
我真的不确定如何进行。递归是我存在的祸根。
最佳答案
您需要一个循环来打印当前深度的部分并执行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 个常量。或者,更好的是,我们可以将这些值存储在线程本地存储中。无论哪种方式都会在溢出堆栈之前允许更深层次的递归。
关于c - 递归打印大纲的部分和小节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29184456/