我想我已经掌握了 Javascript 中的递归,但希望能对我正在阅读的书中评论的特定递归代码有一些清晰的了解
据我了解,下面的代码将执行几个步骤,如果您能纠正我理解中的任何错误,我将对此进行解释,我将非常感激:
findSolution 函数正在寻找一个解决方案,您可以 加 5 或乘以 3 得到 24
函数 find 是递归恰好找到 this 的地方 解决方案,语句
if (start == target)
告诉 当找到解决方案时递归结束并返回历史记录 这是怎么发生的第 8-9 行中的 return 语句以 (1 + 5) 开头,等于 6, 所以它然后从顶部开始继续执行 if 不满足的语句则继续执行 return 语句 这次再次使用 (6 + 5) 等于 11
它将继续执行此操作,直到满足其中一个 if 语句。什么时候 起始值高于目标值,然后函数继续执行 || 的另一边语句并以 (1 * 3) 开头 历史相当于“(1 * 3)”
我不确定的是,为什么函数会在下一次迭代中执行第一部分,将 5 加到 (1 * 3) 中,该函数如何知道加 5,然后在下一次迭代中乘以 3?为什么不继续加5然后一直加到太大返回null?
function findSolution(target) {
function find(start, history) {
if (start == target)
return history;
else if (start > target)
return null;
else
return find(start + 5, "(" + history + " + 5)") ||
find(start * 3, "(" + history + " * 3)");
}
return find(1, "1");
}
console.log(findSolution(24));
// → (((1 * 3) + 5) * 3)
最佳答案
也许这可以让我们更清楚地了解发生了什么。
我刚刚向 find
函数添加了一个 深度
参数来确定递归深度,以及一个 console.log()
记录所有递归调用。
function findSolution(target) {
//added a depth-property to show the recursion better
function find(start, history, depth) {
//simply log all calls in order
console.log("%s%d == %s", "| ".repeat(depth), start, history);
if (start == target)
return history;
else if (start > target)
return null;
else
return find(start + 5, "(" + history + " + 5)", depth+1) ||
find(start * 3, "(" + history + " * 3)", depth+1);
}
return find(1, "1", 0);
}
console.log(findSolution(24));
关于javascript - 我试图理解这个递归代码并且陷入困境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41731494/