需求:給定一個陣列,取出指定數量的元素組合成新陣列,所有組合唯一不重複。這是典型的「組合數學」問題,本文提供遞迴實作範例。
<?php
$arr = array(1, 2, 3, 4, 5);
$target_count = 5; // 要取幾個元素
$results = [];
$total = 0;
function combine($current, $index, $source, $target_count, &$results, &$total) {
// 終止條件:已處理完所有源元素
if ($index === count($source)) {
if (count($current) === $target_count) {
$results[] = $current;
$total++;
}
return;
}
// 分支 1:不選擇當前元素
combine($current, $index + 1, $source, $target_count, $results, $total);
// 分支 2:選擇當前元素
$new_current = $current;
$new_current[] = $source[$index];
combine($new_current, $index + 1, $source, $target_count, $results, $total);
}
// 執行組合
combine([], 0, $arr, $target_count, $results, $total);
// 輸出結果
echo "<pre>";
print_r($results);
echo "</pre>";
echo "總組合數: $total";
?>
輸出 1 筆組合(5 選 5 只有一種):
Array
(
[0] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
)
總組合數: 1
將 $target_count = 3,輸出 10 筆組合:
Array
(
[0] => Array ( [0] => 1 [1] => 2 [2] => 3 )
[1] => Array ( [0] => 1 [1] => 2 [2] => 4 )
[2] => Array ( [0] => 1 [1] => 3 [2] => 4 )
[3] => Array ( [0] => 1 [1] => 2 [2] => 5 )
...
)
總組合數: 10
yield 避免記憶體爆炸array_combinations()(需安裝擴展)組合數公式:C(n,k) = n! / (k! × (n-k)!)