JS递归与||运算符执行逻辑疑问:findSolution函数运行步骤求解
JS递归findSolution函数执行流程解析
核心疑问解答
你困惑的current=6、history="(1 + 5)"执行阶段的出现,是由JavaScript||逻辑运算符的左优先短路执行规则,结合递归回溯逻辑共同导致的,不存在逻辑异常。
完整执行步骤梳理
函数的递归逻辑是:每一层优先尝试+5的分支,只有当前分支所有路径都返回null(也就是走不通),才会回溯去尝试同层*3的分支,具体执行流程如下:
- 顶层调用
findSolution(13)触发初始递归:find(1, "1")- current=1 < 13,优先执行
||左侧的find(1 + 5, "(1 + 5)"),也就是你看到的current=6的调用入口
- current=1 < 13,优先执行
- 进入
find(6, "(1 + 5)")分支- current=6 < 13,优先执行左分支
find(6 + 5, "((1 + 5) + 5)")
- current=6 < 13,优先执行左分支
- 进入
find(11, "((1 + 5) + 5)")分支- current=11 < 13,优先执行左分支
find(11 + 5, "(((1 + 5) + 5) + 5)") - current=16 > 13,返回
null - 左分支返回假值,触发同层右分支
find(11 * 3, "(((1 + 5) + 5) * 3)") - current=33 >13,返回
null - 本层所有路径走不通,返回
null || null = null,回溯到上一层find(6, ...)
- current=11 < 13,优先执行左分支
- 回到
find(6, "(1 + 5)")分支- 左分支返回
null,触发右分支find(6 * 3, "((1 + 5) * 3)") - current=18 >13,返回
null - 本层所有路径走不通,返回
null || null = null,回溯到最顶层find(1, "1")
- 左分支返回
- 回到
find(1, "1")分支- 左分支返回
null,触发右分支find(1 * 3, "(1 * 3)")
- 左分支返回
- 进入
find(3, "(1 * 3)")分支- current=3 <13,优先执行左分支
find(3 +5, "((1 * 3) + 5)")
- current=3 <13,优先执行左分支
- 进入
find(8, "((1 * 3) + 5)")分支- current=8 <13,优先执行左分支
find(8 +5, "(((1 * 3) + 5) + 5)") - current=13 等于目标值,直接返回当前history字符串
(((1 * 3) + 5) + 5)
- current=8 <13,优先执行左分支
- 所有上层递归因为
||左侧已经拿到真值,直接向上返回结果,最终输出对应表达式。
补充说明
你误以为current=6的分支会直接终止,大概率是混淆了分支的执行顺序:||永远先执行左侧表达式,只有左侧返回假值才会执行右侧,所以初始调用一定会先走+5的分支进入current=6的逻辑,不会直接跳去走*3的分支。
内容的提问来源于stack exchange,提问作者GeKtoRiX
相关产品推荐
相关产品推荐

