带循环的递归(生成数据)
您好,我需要知道是否可以通过递归做这样的事情以及如何做? 我希望能够选择我想要的循环数量,例如 GenerateNumbers(x)
其中 x 是我内部的循环数量。
int a, b, c;
for (a = 0; a < 10; a++)
{
printf("\n%d", a);
for (b = 0; b < 10; b++)
{
printf("\n%d%d", a, b);
for (c = 0; c < 10; c++)
{
printf("\n%d%d%d", a, b, c);
}
}
}
Hello I need to know if it is possible to do something like this with recursion and how?
I want to be able to choose how many loops I want, for instance GenerateNumbers(x)
where x is numbers of loops I have inside.
int a, b, c;
for (a = 0; a < 10; a++)
{
printf("\n%d", a);
for (b = 0; b < 10; b++)
{
printf("\n%d%d", a, b);
for (c = 0; c < 10; c++)
{
printf("\n%d%d%d", a, b, c);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
像这样的东西吗?
(注意:这是 C 代码,因为您在示例中使用了
printf
;如果是 C++,则状态数组必须包装在像这样的智能指针中C++0x 中的 std::auto_ptr
或std::unique_ptr
)请注意,您也可以通过迭代来模拟这种递归,请参阅例如 我的另一个答案。
Something like this?
(notice: this is C code, since you used
printf
in your example; if it were C++ the state array would have to be wrapped in a smart pointer likestd::auto_ptr
orstd::unique_ptr
in C++0x)Notice that you can emulate this kind of recursion also with iteration, see for example this other answer of mine.
这确实是可能的。如果 x 存在上限,则需要使用堆栈结构或至少使用数组。
It is indeed possible. You need to use a stack structure or at the very least an array if there is an upper bound on x.