Recursion is an important programming technique. This method allows a function to invoke itself from within. An example is calculating the factorial. The factorial of 0 is specifically defined as 1. The factorial of a larger number is calculated by calculating 1 * 2 * ... To obtain, increase each time by 1, until the number to calculate its factorial is reached.
Algorithm principle
If p represents the full arrangement of n elements, and Pi means that n elements do not contain the full permutation of element I, (i) pi indicates the arrangement of the prefix I in front of the permutation pi, then the full arrangement of n elements is recursively defined as:
① 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.
Code implementation
The code is as follows:
function rank ($base, $temp =null) { $len = strlen ($base); if ($len <= 1) { echo $temp. $base. ' <br/> '; } else {for ($i =0; $i < $len; + + $i) { rank (substr ($base, 0, $i). substr ($base, $i +1, $len-$i-1), $temp . $base [$i]);}} Rank (' 123 ');
However, after several tests of the results of the operation, it was found that there was a problem: if the same element exists, then the whole permutation is repeated.
For example, there are only three cases of the full arrangement of ' 122 ': ' 122 ', ' 212 ', ' 221 ';
Slightly modified, add a judge to repeat the flag, resolved the problem (code below):
The code is as follows:
function Fsrank ($base, $temp =null) {Static $ret = array (); $len = strlen ($base); if ($len <= 1) {//echo $temp. $base. ' <br/> '; $ret [] = $temp. $base; } else {for ($i =0; $i < $len; + + $i) {$had _flag = false; for ($j =0; $j < $i; + + $j) {if ($base [$i] = = $base [$j]) {$had _ Flag = true; Break }} if ($had _flag) {continue; } fsrank (substr ($base, 0, $i). substr ($base, $i +1, $len-$i-1), $temp. $base [$i]); }} return $ret;} print ' <pre> ';p rint_r (Fsrank (' 122 '));p rint ' </pre> ';