首页 > 解决方案 > 递归函数未按预期返回值

问题描述

在这个函数中,我试图计算方法的数量,一个数字可以被解码。1 应该被解码为 a, 3 为 c, 26 为 z 。该函数计算正确的计数,但只返回未定义的。我认为它应该在正确的时间取消递归调用,然后我到达“转义”块,但该数字没有按应有的方式返回。谁能指出我的原因,为什么会这样?

function numWaysDecodable(msg) {
    msg = msg.toString().split("");

    function helper(msg, past = 99, count = 1) {
        if (msg.length === 0) {
            console.log("wtf count is:"+count);
            return count;
        }
        let head = msg.shift();
        if (head < 7 && past < 3) {
            count++
        } 
        //the below return statement was missing           
        return helper(msg, head, count);
    }
    return helper(msg);
}

console.log(numWaysDecodable(123));
固定代码仍然有问题,因为该算法在其他输入方面存在缺陷。例如对于输入 1212,我们返回 4,即使我们应该收到结果 5:

  1. 12 1 2;
  2. 1 2 12;
  3. 12 12;
  4. 1 2 1 2;
  5. 1 21 2;

我认为代码错过了 nr.3,12 12; 我不确定如何解决这个问题。还有一些想法要做

标签: javascriptnode.js

解决方案


您必须在递归函数的每次调用中返回值,例如:

return helper(msg, head, count);

function numWaysDecodable(msg) {
    msg = msg.toString().split("");

    function helper(msg, past = 99, count = 1) {
        if (msg.length === 0) {
            console.log("wtf count is:"+count);
            return count;
        }
        let head = msg.shift();
        if (head < 7 && past < 3) {
            count++
        }            
        return helper(msg, head, count);
    }
    return helper(msg);
}

console.log(numWaysDecodable(123));


推荐阅读