一个php实现的生成排列的算法

来源:互联网 发布:外观设计建模软件 编辑:程序博客网 时间:2024/06/06 05:47
<?phpfunction perm($s, $n, $index){     if($n == 0)     {         return '';    }       else    {           $nIndex = count($index);    //可用的字符串下标        $res = array();        foreach($index as $i => $v)         {               $tmp = $index;            unset($tmp[$i]);        //去掉当前的前缀            /* 调试信息,便于理解            echo "len $n , cur $i , index:\n";            var_dump($tmp);             */            $ret = perm($s, $n-1, $tmp);   //递归得到稍短的排列            if($ret != '')             {                   foreach($ret as $r)                 {                       $res[] = $s[$v] . $r;   //将稍短的排列逐个拼上当前的前缀                }               }               else            {                   $res[] = $s[$v];            }           }           return $res;    }   }function getPerm($s){    $n = strlen($s);    $index = range(0, $n-1);    //得到不同长度的排列    for($i=1; $i<=$n; $i++)    {           var_dump(perm($s, $i, $index));    }   }getPerm('abcd');?>