查找等于数组中总和的数字

时间:2010-04-22 03:02:25

标签: php algorithm

我想在数组X中找到第一组整数,其总和等于给定的数字N
例如:

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

到目前为止我所拥有的: 警告,我知道它使用全局而且很糟糕,这不是问题的关键。

<?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();

?>

当我找到解决方案时,我不知道如何阻止这个过程。我知道我离解决方案并不远。

提前致谢

1 个答案:

答案 0 :(得分:3)

如果您的问题只是如何摆脱递归,请让函数返回一个布尔值,如果它找到了匹配项:

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;
}

(由于它是多余的,我遗漏了你的第二部分)