数组中所有可能的组合 - 递归? [英] All possible combinations in array - recursion?
本文介绍了数组中所有可能的组合 - 递归?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个疑问,希望有人能帮忙.我认为它可能必须通过递归和/或排列来解决,但我不是一个 (PHP) 程序员.
I have a question that goes over my head, hope someone can help. I think it may have to be solved by recursion and/or permutations, but I am not good enough of a (PHP) programmer for that.
$map[] = array("0", "1", "2", "3");
$map[] = array("4", "5", "6", "7");
$map[] = array("8", "9", "10", "11");
$map[] = array("12", "13", "14", "15");
$map[] = array("16", "17", "18", "19");
$map[] = array("20", "21", "22", "23");
$map 数组的最大长度限制为6".
The $map array is limited to a max length of "6".
我正在寻找一种方法来进行所有可能的组合.以下是一些有效的组合:
I am looking for a way to make all possible combinations. Here are a few VALID combinations:
示例 1:
$map[] = array("0", "1", "2", "3", "4", "5", "6", "7");
$map[] = array("8", "9", "10", "11");
$map[] = array("12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", );
$map[] = array("23");
示例 2:
$map[] = array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23");
示例 3:
$map[] = array("0", "1");
$map[] = array("2", "3", "4", "5", "6", "7", "8");
$map[] = array("9", "10", "11");
$map[] = array("12");
$map[] = array("13", "14", "15", "16", "17", "18", "19", "20");
$map[] = array("21", "22", "23");
每个映射数组中的值必须按升序排列,例如此示例无效:
The values in each of the map arrays have to be in ascending order, e.g. this example is INVALID:
$map[] = array("0", "1", "4");
$map[] = array("3", "5");
etc...
希望可以做到.
推荐答案
递归解决方案.
<?php
function combination($remaining, $current, $combinations) {
$e = array_shift($remaining);
$combinations[$current][] = $e;
if(empty($remaining)) {
print_r($combinations);
return;
}
combination($remaining, $current, $combinations);
// 6 Limit remove for all solutions
if ($current < 6) {
combination($remaining, $current + 1, $combinations);
}
}
$remaining = range(0, 23);
combination($remaining, 0, array());
如果你想存储 [0,23] 的所有解,你会很不高兴.
If you want to store all solutions for [0,23] you're gonna have a bad time.
这篇关于数组中所有可能的组合 - 递归?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文