javascript - 为什么这个递归会按照它的方式执行?
问题描述
代码片段来自 Eloquent Javascript:
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(13));
我调试了代码,看看我是否能理解它。没用。
我检查了调用堆栈。似乎在“return null;”之后,程序执行了之前的调用,但这次考虑else return as“call1 is null || call2”。
通过调用堆栈返回两次后(此时 current 为 6,history 为“(1 + 5)”),call1 不再返回 null(因为 current 为 6,history 为“(1 + 5)”),所以current 和 history 如何从 call1 中获取值并使用这些值执行 call2 ?
此外,程序如何决定首先执行 call2 ,因为此时 call1 不返回 null ?(我正在想象一个无限递归,但无论出于何种原因,显然不是这样)
我错过了什么?
解决方案
findSequence(13)
find(1, "1")
find(1 + 5, "(1 + 5)") // this becomes null, because both of its nested stacks are null, because both of their nested stacks are null
find(6 + 5, "((1 + 5) + 5)") // this becomes null, because both of its nested stacks are null
find(11 + 5, "(((1 + 5) + 5) + 5)"
current > target: return null
find(11 * 3, "(((1 + 5) + 5) * 3)"
current > target: return null
find(6 * 3, "((1 + 5) * 3)") // this becomes null, because both of its nested stacks are null
find(18 + 5, "(((1 + 5) * 3) + 5)")
current > target: return null
find(18 * 3, "(((1 + 5) * 3) * 3)")
current > target: return null
find(1 * 3, "(1 * 3)")
find(3 + 5, "((1 * 3) + 5)")
find(8 + 5, "(((1 * 3) + 5) + 5)")
current == target: return "(((1 * 3) + 5) + 5)"
那么,你会说这是准确的吗?
推荐阅读
- python - 如何在 Flask 应用程序中拥有一个线程安全的全局对象?
- typescript - 为什么 TS 不让我索引到兼容的对象类型?
- python - 通过 GET 或 POST 请求向表单发送一些值
- r - 在 R 中识别数据框中的异常值
- c++ - 在同一对象内插入向量
- php - 使用 Guzzle 发送文件
- mongodb - 如何在不更新值的情况下修改值,然后将其与 mongodb 中的元素匹配?
- django-models - Django rest框架详细获取验证错误对象
- networking - 无法从主机连接到 Vagrant 专用网络 - 无法访问目标主机
- c - 在位域中,为什么有些位中间是空的?