Dizideki bir toplamına eşittir numaralar bulun

1 Cevap php

I want to find the first set of integers in an array X that the sum equals a given number N.
For example:

X = {5, 13, 24, 9, 3, 3}
N = 28
Solution = {13, 9, 3, 3}

Here what I have so far : WARNING, I know it uses global and it is bad,that's not the point of the question.

<?php

function s($index = 0, $total = 0, $solution = '')
{
    global $numbers;
    global $sum;

    echo $index;

    if($total == 28)
    {
        echo '<br/>'.$solution.' = '.$sum.'<br/>';
    }
    elseif($index < count($numbers) && $total != 28)
    {
        s($index + 1, $total, $solution);
        s($index + 1, $total + $numbers[$index], $solution.' '.$numbers[$index]);
    }
}

$numbers = array(5, 13, 24, 9, 3, 3);
$sum = 28;

s();

?>

Ben çok iyi bir çözüm değil ben biliyorum .. bu çözüm bulduğunda ben sürecini durdurmak nasıl alamadım ..

Şimdiden teşekkürler

1 Cevap

Soru özyineleme patlak ne kadar ise, işlev bir maç ya da değil Eğer bulunursa için bir boolean dönün:

function s($index = 0, $total = 0, $solution = '')
{
    global $numbers;
    global $sum;

    echo $index;

    if($total == 28)
    {
        echo '<br/>'.$solution.' = '.$sum.'<br/>';
        return true;
    }
    elseif($index < count($numbers))
    {
        return s($index + 1, $total, $solution) or s($index + 1, $total + $numbers[$index], $solution.' '.$numbers[$index]);
    }

    return false;
}

(Gereksiz beri ben senin else ikinci kısmını sol)