Algorithm Description: If p is used to denote the full arrangement of n elements, and Pi means that n elements do not contain the full permutation of element I, (i) pi denotes the arrangement of the prefix I in front of the permutation pi, then the full arrangement of n elements can be defined recursively:
① if n=1, then the permutation p has only one element i;
② if n>1, then the entire arrangement p is composed of the permutation (i) pi;
By definition, you can see that if you have generated the permutation pi for (k-1) elements, then the arrangement of the K elements can be generated by adding element I to each pi.
1.
1<?PHP2 functionRank$base,$temp=NULL)3 {4 $len=strlen($base);5 if($len<= 1)6 {7 Echo $temp.$base.‘ <br/> ';8 }9 ElseTen { One for($i= 0;$i<$len; ++$i) A { -Ranksubstr($base, 0,$i).substr($base,$i+1,$len-$i-1),$temp.$base[$i]); - } the } - } -Rank (' 123 ');
However, there is a problem with this algorithm: if there is the same element, then there is a full array of duplicates. For example, there are only three cases of the full arrangement of ' 122 ': ' 122 ', ' 212 ', ' 221 ';
2, the above algorithm based on the price of the re-operation can be
1<?PHP2 functionFsrank ($base,$temp=NULL)3 {4 Static $ret=Array();5 $len=strlen($base);6 if($len<= 1)7 {8 //echo $temp. $base. ' <br/> ';9 $ret[] =$temp.$base;Ten } One Else A { - for($i= 0;$i<$len; ++$i) - { the $had _flag=false; - for($j= 0;$j<$i; ++$j) - { - if($base[$i] ==$base[$j]) + { - $had _flag=true; + Break; A } at } - if($had _flag) - { - Continue; - } -Fsrank (substr($base, 0,$i).substr($base,$i+1,$len-$i-1),$temp.$base[$i]); in } - } to return $ret; + } - Print' <pre> '; the Print_r(Fsrank (' 122 ')); * Print' </pre> '; $?>
Full array of PHP implementations (recursive algorithm)