我知道有几个问题涉及到这个主题(例如这里),但没有一个(至少从我发现的)能满足我的需要。
假设我有一个3个元素的数组[1, 2, 3]
。我需要找到所有可能的唯一组合(所以不包括排列,像这里),包括重复元素的组合。所以结果应该是:
[1]
[2]
[3]
[1, 1]
[1, 2]
[1, 3]
[2, 2]
[2, 3]
[3, 3]
[1, 1, 1]
[1, 1, 2]
[1, 1, 3]
[1, 2, 2]
[1, 2, 3]
[1, 3, 3]
[2, 2, 2]
[2, 2, 3]
[2, 3, 3]
[3, 3, 3]
排除[3, 2, 1]
或[2, 1, 3]
等子集,它们与[1, 2, 3]
相同。
我怎样才能做到这一点?
使用递归的快速解决方案,可能不是最好的方法,但它可以完成工作。
<?php
$arr = array(1,2,3);
$result = array();
function combinations($arr, $level, &$result, $curr=array()) {
for($i = 0; $i < count($arr); $i++) {
$new = array_merge($curr, array($arr[$i]));
if($level == 1) {
sort($new);
if (!in_array($new, $result)) {
$result[] = $new;
}
} else {
combinations($arr, $level - 1, $result, $new);
}
}
}
for ($i = 0; $i<count($arr); $i++) {
combinations($arr, $i+1, $result);
}
// TEST
foreach ($result as $arr) {
echo join(" ", $arr) . '<br>';
}
?>