我已经搜索了一段时间,试图找到某种解决方案来解决目前阻碍我完成任务的问题。我在其他编程语言中遇到了一些解决方案,尽管我尝试过,但我真的无法理解。我还看到了很多关于这个问题的术语,如排列、重构、子集和、一美元硬币等。
如果我的做法不对,请随时告诉我。
简而言之,问题是:
给定一组(数组)数字,例如:CCD_ 1,我怎么能找到这些数字的组合加起来(或等于)一个特定的和,例如:14
。
以上示例数字的一些潜在组合示例:
3 + 3 + 3 + 3 + 2
7 + 3 + 2 + 2
7 + 7
14
由于我试图解决的问题是在PHP中,如果有一个可以用该语言提供的解决方案,我会很高兴。如果没有,即使有人能更好地解释我试图解决的问题是什么,以及潜在的解决方法,我也会非常感激。
或者,如果我可能走错了路,我会洗耳恭听的。
要生成所有解决方案,您需要使用某种回溯,"猜测"第一个数字是否在解决方案中,并对每种可能性进行递归(需要对结果求和,或者不需要)。
类似以下伪代码:
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
以下是我迄今为止根据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);