这就是我得到的:
<?php
// Program to print all
// combination of size r
// in an array of size n
function printCombinations($arr, $n, $r) {
$data = [];
combinationUtil($arr, $data, 0, $n - 1, 0, $r);
}
function combinationUtil($arr, $data, $start, $end, $index, $r) {
if ($index == $r) {
for ($j = 0; $j < $r; $j++) {
echo $data[$j];
}
echo "<br>";
return;
}
for ($i = $start; $i <= $end && $end - $i + 1 >= $r - $index; $i++) {
$data[$index] = $arr[$i];
combinationUtil($arr, $data, $i + 1, $end, $index + 1, $r);
}
}
$arr = [
1,
2,
3,
4,
5
];
$r = 3;
$n = count($arr);
printCombinations($arr, $n, $r);
它给出此输出:
123
124
125
134
135
145
234
235
245
345
我需要的是:
123
124
125
132
134
135
142
143
145
152
153
154
213
214
215
231
234
235
241
243
245
251
253
254
312
314
315
321
324
325
341
342
345
351
352
354
412
413
414
415
421
423
425
431
432
435
451
452
453
512
513
514
521
523
524
531
532
534
541
542
543
您可以使用递归方法,在数组上进行迭代,并在每次迭代中通过删除当前元素并在其之前添加返回的变体来调用自身。
类似这样的东西:
<?php
function variation_without_repetition ($array,$items){
if($items == 0 || count($array) == 0) return [[]];
$variations = [];
foreach($array as $index => $item){
$array_remaining = $array;
array_splice($array_remaining,$index,1);
foreach(variation_without_repetition($array_remaining,$items - 1) as $variation){
array_unshift($variation,$item);
$variations[] = $variation;
}
}
return $variations;
}
$variations = variation_without_repetition([1,2,3,4,5], 3);
foreach($variations as $variation){
echo implode($variation);
echo "<br>\n";
}
?>