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

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

本文介绍了在数组中查找等于总和的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是我目前所拥有的:警告,我知道它使用 global 并且很糟糕,这不是问题的重点.

当它找到解决方案时,我不知道如何停止该过程..我知道我离好的解决方案不远了..

提前致谢

解决方案

如果你的问题只是如何突破递归,让函数返回一个布尔值来判断是否找到匹配:

function s($index = 0, $total = 0, $solution = ''){全球 $numbers;全局 $sum;回声 $index;if($total == 28){echo '<br/>'.$solution.'= '.$sum.'<br/>';返回真;}elseif($index < count($numbers)){返回 s($index + 1, $total, $solution) 或 s($index + 1, $total + $numbers[$index], $solution.' '.$numbers[$index]);}返回假;}

(我省略了 else 的第二部分,因为它是多余的)

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

?>

I don't get how I can stop the process when it finds the solution.. I know I am not far from good solution..

Thanks in advance

解决方案

If your question is just how to break out of the recursion, have the function return a boolean for if it's found a match or not:

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

(I left out the second part of your else since it's redundant)

这篇关于在数组中查找等于总和的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 17:35