php递归函数返回数组


php recursive function return array

这里是原始函数(递归函数):

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>';
} 

将其更改为返回字符串数组,而不是在函数中直接回显?

试试这个(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);