1

即使 sum === 在子集()中最大,我的控制台中也没有得到“真”。true 只发送回调用函数?那么我如何让“return 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])
4

1 回答 1

1
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])
于 2013-08-29T17:28:44.833 回答