gpt4 book ai didi

php - 数组中所有可能的组合 - 递归?

转载 作者:行者123 更新时间:2023-12-05 07:59:31 26 4
gpt4 key购买 nike

我有一个问题一直困扰着我,希望有人能提供帮助。我认为它可能必须通过递归和/或排列来解决,但我不是一个足够好的 (PHP) 程序员。

$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”。

我正在寻找一种方法来进行所有可能的组合。以下是一些有效的组合:

示例 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");

每个 map 数组中的值必须按升序排列,例如这个例子是无效的:

$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] 的所有解决方案,你会遇到麻烦。

关于php - 数组中所有可能的组合 - 递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21556945/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com