即使sum ===在subset()中最大,我的控制台也没有得到“ true”。真只发送回调用函数吗?那么,如何获得“返回真”的行为,就像新手期望的那样?

function ArrayAdditionI(arr)
{
    arr.sort();
    var largest = arr.pop()
    subset([], arr, largest);
}


function subset(soFar, rest, largest)
{
    var sum = 0;
    if (rest.length === 0)
    {
        for(var i=0; i<soFar.length; i++)
        {
            sum+= soFar[i];
        }
        if (sum === largest)
        {
            return true;
        }
    }

    else
    {
        var soFar2 = soFar.slice(0);
        soFar2.push(rest[0]);
        subset(soFar,rest.slice(1),largest);
        subset(soFar2, rest.slice(1),largest);
    }
}


ArrayAdditionI([85,3,88,2])

最佳答案

function ArrayAdditionI(arr)
{
    arr.sort();
    var largest = arr.pop()
    var ret = subset([], arr, largest);
    // do something with ret
}


function subset(soFar, rest, largest)
{
    var sum = 0;
    if (rest.length === 0)
    {
        for(var i=0; i<soFar.length; i++)
        {
            sum+= soFar[i];
        }
        if (sum === largest)
        {
            return true;
        }
    }

    else
    {
        var soFar2 = soFar.slice(0);
        soFar2.push(rest[0]);
        subset(soFar,rest.slice(1),largest);
        subset(soFar2, rest.slice(1),largest);
    }
    return false;
}


ArrayAdditionI([85,3,88,2])

10-07 21:08