【问题标题】:php recursive function return arrayphp递归函数返回数组
【发布时间】:2015-04-27 01:15:47
【问题描述】:

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

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

改成返回字符串数组,而不是直接在函数中回显?

【问题讨论】:

    标签: php arrays recursion return


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2021-08-14
      • 2013-09-21
      • 1970-01-01
      • 1970-01-01
      • 2012-03-11
      • 2019-01-12
      • 2011-03-29
      • 2015-10-23
      • 2018-01-04
      相关资源
      最近更新 更多