【发布时间】:2018-10-10 05:46:06
【问题描述】:
我知道递归函数的通用模板需要针对每种情况的 return 语句。考虑这个递归函数,如果给定的整数列表可以通过算术运算符(*,/,+,-)得到 24,它应该(但不能)返回 true。
static boolean doArith(List<Double> A, double temp, int start) {
// base case
if (start == A.size()) return temp == 24;
// recursive calls
for (int op = 0; op < 4; op++) {
doArith(A,
arith(temp,op,A.get(start)),
start+1);
}
return false;
}
通过基本案例块中的打印语句,我确定我的代码正确识别了 24 的生成时间。但是,当调用堆栈解析时,它无法返回 true。
我尝试重构代码,甚至将 for 循环硬编码为 4 个单独的调用,但正如预期的那样,这不起作用。
(编辑:回应@Caramiriel评论)我尝试将函数重写为:
static boolean doArith(List<Double> A, double temp, int start) {
// base case
if (start == A.size()) return temp == 24;
boolean b = false;
// recursive calls
for (int op = 0; op < 4; op++) {
b = doArith(A,
arith(temp,op,A.get(start)),
start+1);
}
return b;
}
但这仍然总是返回false。
如何让这个函数在遇到这种情况时返回true?
谢谢
【问题讨论】:
-
您没有在循环内处理来自
doArith()的结果值。 -
我试过了,但没用。我会将其添加到编辑中
-
在for循环中,检查b是否为真,返回b
标签: recursion return boolean terminate callstack