- 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]);
- }
- }
- }
- Rank (' 123 ');
- ?>
Copy CodeHowever, 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 logo, problem solving.
- 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)
- {
- 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 '
'; - Print_r (Fsrank (' 122 '));
- print '
';
- ?>
Copy CodeThis paper introduces the recursive algorithm of the whole arrangement, here we recommend a full array of PHP arrays of non-recursive algorithm implementation code, we can refer to the next. |