繁体   English   中英

查找总和的潜在数字组合(给定要选择的数字)

[英]Finding potential combinations of numbers for a sum (given a number set to select from)

我一直在寻找一段时间以尝试找到某种解决方案,以解决当前阻碍我要完成的任务的问题。 我遇到了一些其他编程语言的解决方案,尽管我曾尝试这样做,但这些解决方案我还是听不懂。 我还看到了很多围绕此问题的术语,例如排列,重构,子集总和,1美元硬币等。

如果我使用错误的方法,请随时告诉我。

简而言之,这就是问题所在:

给定一组数字(数组),例如: 2, 3, 7, 14我如何找到这些数字的哪些组合加起来(或等于)一个特定的总和,例如: 14

上述示例编号的一些可能组合的示例:

3 + 3 + 3 + 3 + 2
7 + 3 + 2 + 2
7 + 7
14

由于我要解决的问题是在PHP中 ,所以我很乐意提供该语言的解决方案。 如果没有,即使有人可以更好地解释我要解决的问题是什么,以及这样做的潜在方法,我也将不胜感激。

再或者,如果我可能会以错误的方式进行操作,我会全神贯注。

到目前为止,根据amit的反馈和示例以及其他一些示例,这是我设法解决的问题。 到目前为止,它似乎正在工作-但我不确定100%。

$totals = array();
$x=0;

function getAllCombinations($ind, $denom, $n, $vals=array()){
    global $totals, $x;
    if ($n == 0){
        foreach ($vals as $key => $qty){
            for(; $qty>0; $qty--){
                $totals[$x][] = $denom[$key];
             }
        }
        $x++;
        return;
    }
    if ($ind == count($denom)) return;
    $currdenom = $denom[$ind];
    for ($i=0;$i<=($n/$currdenom);$i++){
        $vals[$ind] = $i;
        getAllCombinations($ind+1,$denom,$n-($i*$currdenom),$vals);
    }
}

$array = array(3, 5, 7, 14);
$sum = 30;

getAllCombinations(0, $array, $sum);

var_dump($totals);

要生成所有解决方案,您将需要使用某种回溯,如果第一个数字是否在解决方案中,则进行“猜测”,并针对每种可能性进行递归(需要对结果求和,或者不对结果求和)。

类似于以下伪代码:

genResults(array, sum, currentResult):
   if (sum == 0): //stop clause, found a series summing to to correct number
         print currentResult
   else if (sum < 0): //failing stop clause, passed the required number
         return
   else if (array.length == 0): //failing stop clause, exhausted the array
         return
   else:
         //find all solutions reachable while using the first number (can use it multiple times)
         currentResult.addLast(array[0])
         genResults(array, sum - array[0], currentResult)
         //clean up
         currentResult.removeLast() 
         //find all solutions reachable while NOT using first number
         genResults(array+1, sum, currentResult)
         //in the above array+1 means the subarray starting from the 2nd element

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM