如何获得给定数字的所有可能组合。 比如我有
$arr = [ 1, 2, 3, 4]
我想在组合中没有任何重复的组合
[1] => [1]
[2] => [2]
[3] => [3]
[4] => [4]
[5] => [1, 2]
[6] => [1, 3]
[7] => [1, 4]
[8] => [2, 3]
[9] => [2, 4]
[10] => [3, 4]
[11] => [1, 2, 3]
[12] => [1, 2, 4]
[13] => [1, 3, 4]
[14] => [2, 3, 4]
[15] => [1, 2, 3, 4]
答案 0 :(得分:3)
我希望下面的函数按照你预期的输出工作:
function get_array_combination($arr) {
$results = array(array( ));
foreach ($arr as $values)
foreach ($results as $combination)
array_push($results, array_merge($combination, array($values))); // Get new values and merge to your previous combination. And push it to your results array
return $results;
}
$set = array('1', '2', '3', '4');
$final_array = get_array_combination($set);
echo "<pre>";
print_r(array_values(array_filter($final_array))); // Removed blank entry from array and re indexing array keys.
答案 1 :(得分:0)
我不喜欢给定的解决方案在其循环内修改迭代变量,而且我想要一个易于理解的解决方案,以移植到其他语言。所以在这里:
<?php
function permutation(array $arr)
{
$out=[[]];
foreach($arr as $key2=> $item2){
$copy=$out;
foreach($copy as $k=> $v){
array_push($copy[$k],$item2 );
}
array_push($out,...$copy);
}
return $out;
}
print_r(permutation(array(1,2,3,4)));
第二个目的是使我们更好地了解正在发生的事情。
<?php
function permutation(array $arr)
{
$out=[];
while(count($arr)){
$out_temp=[[]];
foreach($arr as $key2=> $item2){
$copy=$out_temp;
foreach($copy as $k=> $v){
array_push($copy[$k],$item2 );
}
if($key2==0){
unset($out_temp[0]);
}
array_push($out_temp,...$copy);
}
array_push($out,...$out_temp);
array_shift($arr);
}
return $out;
}
print_r(permutation(array(1,2,3,4,5)));