递归实现:验证指定数字能否通过加5/乘3序列生成并输出操作序列
解决递归生成数字的操作序列输出问题
嘿,我来帮你搞定这个问题!你现有的tester函数只能判断目标数字是否能通过加5或乘3生成,但没法输出具体的操作步骤对吧?咱们来改造一下这个函数,让它不仅能给出判断结果,还能把生成路径完整返回出来~
原函数的局限
你的原函数只返回1(可以生成)或0(无法生成),没有记录递归过程中的操作路径。我们需要修改函数逻辑,让它在递归时积累操作步骤,找到有效路径后直接返回序列。
改造后的函数(返回操作序列)
下面这个函数会返回一个操作数组,如果目标数字无法生成则返回null:
function findSequence(target, current = 1, sequence = []) { // 找到目标值,返回积累的操作序列 if (current === target) { return sequence; } // 当前值超过目标,这条路走不通 if (current > target) { return null; } // 先尝试「加5」的路径,把操作加入序列 const addPath = findSequence(target, current + 5, [...sequence, '+5']); if (addPath) { return addPath; } // 加5走不通,再尝试「乘3」的路径 const multiplyPath = findSequence(target, current * 3, [...sequence, '*3']); if (multiplyPath) { return multiplyPath; } // 两条路径都无效,返回null return null; }
函数逻辑说明
- 新增了两个参数:
current记录当前递归到的数字(默认起始值1),sequence记录已经执行的操作(默认空数组)。 - 递归终止条件:
- 当
current等于目标值时,直接返回积累的操作序列。 - 当
current超过目标值时,返回null表示该路径无效。
- 当
- 递归尝试顺序:先尝试「加5」操作,如果这条路径能找到有效序列就直接返回;如果不行,再尝试「乘3」操作。
测试示例
// 测试13:预期返回 ['*3', '+5', '+5'] console.log(findSequence(13)); // 测试15:无法生成,返回null console.log(findSequence(15));
进阶:展示每一步的数值变化
如果想更直观地看到每一步的计算过程,可以修改函数,把操作和对应的数值变化一起记录:
function findSequenceWithValues(target, current = 1, sequence = [`初始值: ${current}`]) { if (current === target) { return sequence; } if (current > target) { return null; } const nextAdd = current + 5; const addPath = findSequenceWithValues(target, nextAdd, [...sequence, `${current} +5 → ${nextAdd}`]); if (addPath) { return addPath; } const nextMultiply = current * 3; const multiplyPath = findSequenceWithValues(target, nextMultiply, [...sequence, `${current} *3 → ${nextMultiply}`]); if (multiplyPath) { return multiplyPath; } return null; } // 打印13的生成过程 console.log(findSequenceWithValues(13).join('\n'));
输出结果:
初始值: 1 1 *3 → 3 3 +5 → 8 8 +5 → 13
内容的提问来源于stack exchange,提问作者jeea
相关产品推荐
相关产品推荐

