满足动态条件时退出递归函数 [英] Quit recursive function when a dynamic condition is met
问题描述
void magic(char* str, int i, int changesLeft) {
if (changesLeft == 0) {
printf("%s\n", str);
return;
}
if (i < 0) return;
// flip current bit
str[i] = str[i] == '0' ? '1' : '0';
magic(str, i-1, changesLeft-1);
// or don't flip it (flip it again to undo)
str[i] = str[i] == '0' ? '1' : '0';
magic(str, i-1, changesLeft);
}
我想退出递归函数并返回调用函数发生某种情况(如果发生)。所以这就像我的递归功能是听到可能告诉她退出的声音!
I would like to quit the recursive function and return to the caller function when a certain condition occurs (if it does). So it's like my recursive function is hearing voices that might tell her to quit!
它只发生 str <打印/ code>,此处:
It only happens after str
is printed, here:
if (changesLeft == 0) {
printf("%s\n", str);
int quit_now = voices(str);
return;
}
如何做到这一点(停止展开递归并返回函数调用者) ?
How to do this (stop unfolding the recursion and return to the function caller)?
尝试:
if (i < 0 || quit_now == 1) return;
似乎阻止了执行并且永远不会结束!
just seems to block the execution and never end!
PS - 我甚至对 c感兴趣旧方法。
PS - I am interested even in c old methodologies.
推荐答案
要把它放在最简单的形式,你可以做这样的事情:
To put it in the simplest form, you could do something like this:
void foo(bool & ret) {
// doStuff...
if (ret) return;
foo(ret);
// doStuff...
if (ret) return;
foo(ret);
}
然后你开始递归:
bool ret = false;
foo(ret);
在您的情况下,您可以通过
In your case you can interupt the recursion by
if (!changesLeft) {
printf("%s\n", str);
ret = true;
return;
}
设置为true会让你退出整个调用树。
Setting to true will get you out of the entire call tree.
您也可以在C中执行此操作,只需使用指针而不是引用。
You can do it in C as well, just use a pointer rather than a reference.
这篇关于满足动态条件时退出递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!