【发布时间】:2013-04-25 00:03:48
【问题描述】:
我整天都在看 PHP 数组排列/组合问题.. 仍然无法弄清楚:/
如果我有一个类似的数组:
20 //key being 0
20 //key being 1
22 //key being 2
24 //key being 3
我需要这样的组合:
20, 20, 22 //keys being 0 1 2
20, 20, 24 //keys being 0 1 3
20, 22, 24 //keys being 0 2 3
20, 22, 24 //keys being 1 2 3
我目前拥有的代码:
20, 22, 24
因为它不想重复 20 次……但这正是我所需要的!
这是我的代码。直接来自Php recursion to get all possibilities of strings
function getCombinations($base,$n){
$baselen = count($base);
if($baselen == 0){
return;
}
if($n == 1){
$return = array();
foreach($base as $b){
$return[] = array($b);
}
return $return;
}else{
//get one level lower combinations
$oneLevelLower = getCombinations($base,$n-1);
//for every one level lower combinations add one element to them that the last element of a combination is preceeded by the element which follows it in base array if there is none, does not add
$newCombs = array();
foreach($oneLevelLower as $oll){
$lastEl = $oll[$n-2];
$found = false;
foreach($base as $key => $b){
if($b == $lastEl){
$found = true;
continue;
//last element found
}
if($found == true){
//add to combinations with last element
if($key < $baselen){
$tmp = $oll;
$newCombination = array_slice($tmp,0);
$newCombination[]=$b;
$newCombs[] = array_slice($newCombination,0);
}
}
}
}
}
return $newCombs;
}
我一直在玩($b == $lastEl) 行,没有运气
================
我已经查看过的问题与导致内存不足错误的 OR 不同!:
- How can I get all permutations in PHP without sequential duplicates?
- Permutations - all possible sets of numbers
- Combinations, Dispositions and Permutations in PHP
- PHP array combinations
- Get all permutations of a PHP array?
- PHP: How to get all possible combinations of 1D array?
- Select only unique array values from this array
- Get all permutations of a PHP array?
- PHP: How to get all possible combinations of 1D array?
- Select only unique array values from this array
- How can I get all permutations in PHP without sequential duplicates?
- Algorithm to return all combinations of k elements from n
- Find combination(s) sum of element(s) in array whose sum equal to a given number
- Combinations, Dispositions and Permutations in PHP
- PHP array combinations
- Php recursion to get all possibilities of strings
- How to return permutations of an array in PHP?
- Permutations - all possible sets of numbers
- Subset-sum problem in PHP with MySQL
- Find unique combinations of values from arrays filtering out any duplicate pairs
- Finding all the unique permutations of a string without generating duplicates
- Generate all unique permutations
- Subset sum for exactly k integers?
我已经尝试了其中一些算法,其中包含 12 个项目,但最终内存不足。然而,我目前使用的算法并没有给我一个内存不足的错误....但是..我需要那些重复的!
【问题讨论】:
-
请给出输入数据和预期输出的正确示例。
var_dump()格式适合 -
我终于在 PHP 中找到了一个递归的东西——请看我的回答...
标签: php algorithm recursion permutation combinations