我绝不是声称这是有效的或最佳的。那里有更好的解决方案。但这只是对您问题的直接回答。如果您想消除一些膨胀(以可能会降低一点性能为代价),您可以将getRemainingWords
函数调用替换为:
$index = 0;
array_values(array_filter($words, function($key, &$index) { return !($key == $index++); }));
否则,这里是
function getPossibleCombinations($words) {
$combinations = array();
$count = count($words);
// Base case: if there's only 1 word, there's only one combination
if ($count == 1) {
return array($words);
}
// Otherwise, loop over each words
foreach ($words as $key=>$word) {
// For each item, get all of the remaining items in the array (all except the current one)
$otherWords = getRemainingWords($words, $key);
// And recursively permute them
$otherCombinations = getPossibleCombinations($otherWords);
foreach ($otherCombinations as $otherCombination) {
$combinations[] = array_merge(array($word), $otherCombination);
}
}
return $combinations;
}
function getRemainingWords($array, $index) {
$results = array();
foreach ($array as $key=>$value) {
if ($key == $index) {
continue;
}
$results[] = $value;
}
return $results;
}