这是原始函数(递归函数):
function permute($items, $perms = array())
{
if (empty($items))
{
echo join('', $perms).'<br>';
}
else
{
for ($i = 0; $i < count($items); ++$i)
{
$newitems = $items;
$newperms = $perms;
$foo = implode(array_splice($newitems, $i, 1));
array_unshift($newperms, $foo);
permute($newitems, $newperms);
}
}
}
permute(array("A", 'B', 'C'));
在这种情况下,输出将是:
cba
bca
cab
acb
bac
abc
如何修改此部分:
if (empty($items))
{
echo join('', $perms).'<br>';
}
将其更改为返回字符串数组而不是直接在函数中回显?
答案 0 :(得分:3)
试试这个(IdeOne example):
function permute($items, $perms = array(), $result = array())
{
if (empty($items))
{
$result[] = join('', $perms);
}
else
{
for ($i = 0; $i < count($items); ++$i)
{
$newitems = $items;
$newperms = $perms;
$foo = implode(array_splice($newitems, $i, 1));
array_unshift($newperms, $foo);
$result = permute($newitems, $newperms, $result);
}
}
return $result;
}
$bar = permute(array("A", 'B', 'C'));
var_dump($bar);