Home  >  Article  >  Backend Development  >  一个php兑现的生成排列的算法

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

WBOY
WBOYOriginal
2016-06-13 12:55:32789browse

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

<?php function 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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn