Home >Backend Development >PHP Tutorial >PHP fully arranged recursive algorithm code
Algorithm Principle
If P represents the full arrangement of n elements, and Pi represents the full arrangement of n elements that does not include element i, (i) Pi represents the arrangement with the prefix i in front of the arrangement Pi, then n The total arrangement of elements can be recursively defined as:
① If n=1, then the arrangement P has only one element i;
② If n>1, then the total arrangement P consists of the arrangement (i) Pi;
According to the definition, it can be seen If a permutation Pi of (k-1) elements has been generated, then a permutation of k elements can be generated by adding element i in front of each Pi.
Code implementation
Copy code The code is as follows:
function rank($base, $temp=null)
{
$len = strlen($base);
if($len <= 1)
{
echo $temp. $base.'
';
}
else
{
for($i=0; $i< $len; ++$i)
{
rank(substr($base, 0, $ i).substr($base, $i+1, $len-$i-1), $temp.$base[$i]);
, after multiple test runs, it was found that there is a problem: if there are the same elements, the entire arrangement will be repeated.
For example, there are only three situations for the full arrangement of '122': '122', '212', and '221'; but the above methods are repeated.
Slightly modified, added a flag to identify duplicates, solved the problem (the code is as follows):
Copy the code The code is as follows:
function fsRank($base, $temp=null)
{
static $ret = array();
$ len = strlen($base);
if($len <= 1)
{
//echo $temp.$base.'
';
$ret[] = $temp.$base ;
}
else
{
for($i=0; $i< $len; ++$i)
{
$had_flag = false;
for($j=0; $j<$i; ++ $j)
break;
}
fsRank(substr($base, 0, $i).substr($base, $i+1, $len-$i-1), $temp.$base[$i]); return $ret;
}
print '
';<br>print_r(fsRank('122'));<br>print '';