php实现的生成排列算法示例
本文实例讲述了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<=$n; $i++)
{
var_dump(perm($s, $i, $index));
}
}
getPerm('abcd');
?>
运行结果:
array(4) {
=>
string(1) "a"
=>
string(1) "b"
=>
string(1) "c"
=>
string(1) "d"
}
array(12) {
=>
string(2) "ab"
=>
string(2) "ac"
=>
string(2) "ad"
=>
string(2) "ba"
=>
string(2) "bc"
=>
string(2) "bd"
=>
string(2) "ca"
=>
string(2) "cb"
=>
string(2) "cd"
=>
string(2) "da"
=>
string(2) "db"
=>
string(2) "dc"
}
array(24) {
=>
string(3) "abc"
=>
string(3) "abd"
=>
string(3) "acb"
=>
string(3) "acd"
=>
string(3) "adb"
=>
string(3) "adc"
=>
string(3) "bac"
=>
string(3) "bad"
=>
string(3) "bca"
=>
string(3) "bcd"
=>
string(3) "bda"
=>
string(3) "bdc"
=>
string(3) "cab"
=>
string(3) "cad"
=>
string(3) "cba"
=>
string(3) "cbd"
=>
string(3) "cda"
=>
string(3) "cdb"
=>
string(3) "dab"
=>
string(3) "dac"
=>
string(3) "dba"
=>
string(3) "dbc"
=>
string(3) "dca"
=>
string(3) "dcb"
}
array(24) {
=>
string(4) "abcd"
=>
string(4) "abdc"
=>
string(4) "acbd"
=>
string(4) "acdb"
=>
string(4) "adbc"
=>
string(4) "adcb"
=>
string(4) "bacd"
=>
string(4) "badc"
=>
string(4) "bcad"
=>
string(4) "bcda"
=>
string(4) "bdac"
=>
string(4) "bdca"
=>
string(4) "cabd"
=>
string(4) "cadb"
=>
string(4) "cbad"
=>
string(4) "cbda"
=>
string(4) "cdab"
=>
string(4) "cdba"
=>
string(4) "dabc"
=>
string(4) "dacb"
=>
string(4) "dbac"
=>
string(4) "dbca"
=>
string(4) "dcab"
=>
string(4) "dcba"
}
希望本文所述对大家PHP程序设计有所帮助。
原文链接:https://blog.csdn.net/zhaozhi406/article/details/8531944
文档来源:http://www.zzvips.com/article/183037.html
页:
[1]