我绞尽脑汁想了半天,还是没明白。有人可以向我解释一下,这个功能到底是如何工作的吗?!?!?!
function findSolution(target) {
function find(current, history) {
if (current == target) {
return history;
} else if (current > target) {
return null;
} else {
return find(current + 5, `(${history} + 5)`) ||
find(current * 3, `(${history} * 3)`);
}
}
return find(1, "1");
}
console.log(findSolution(24));
// → (((1 * 3) + 5) * 3)
它如何不不断地在无限循环中来回调用自身?
最佳答案
基本上,该测试:
if (current == target) {
return history;
}
测试是否找到解决方案,然后返回该解决方案
测试时:
if (current > target) {
return null;
}
发现找不到解,然后返回null。
例如,如果您尝试 findSolution(10)
,您将得到 null。
否则,如果我们不处于这些递归结束条件之一,代码将继续搜索并构建解决方案字符串。
因此,此代码将尝试构建“+5”和“*3”的每种可能的组合,直到产生给定的数字,如果该组合给出更大的数字,则返回 null。
关于javascript - JS 中令人沮丧的递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48686988/