Home > Backend Development > PHP Tutorial > PHP fully arranged recursive algorithm code

PHP fully arranged recursive algorithm code

WBOY
Release: 2016-07-25 09:03:27
Original
970 people have browsed it
  1. function rank($base, $temp=null)
  2. {
  3. $len = strlen($base);
  4. if($len <= 1)
  5. {
  6. echo $temp. $base.'
    ';
  7. }
  8. else
  9. {
  10. for($i=0; $i< $len; ++$i)
  11. {
  12. rank(substr($base, 0, $ i).substr($base, $i+1, $len-$i-1), $temp.$base[$i]);
  13. }
  14. }
  15. }
  16. rank('123');
  17. ?> ;
Copy the code

However, after testing the results many times, we found that there is a problem: if there are the same elements, the entire arrangement will be repeated. For example, there are only three possible arrangements for '122': '122', '212', and '221'; but the above methods are repeated. Make slight modifications, add a flag to identify duplicates, and the problem is solved.

  1. function fsRank($base, $temp=null)
  2. {
  3. static $ret = array();
  4. $len = strlen($base);
  5. if($len < = 1)
  6. {
  7. //echo $temp.$base.'
    ';
  8. $ret[] = $temp.$base;
  9. }
  10. else
  11. {
  12. for($i=0; $i< $len; ++$i)
  13. {
  14. $had_flag = false;
  15. for($j=0; $j<$i; ++$j)
  16. {
  17. if($base[$i] = = $base[$j])
  18. {
  19. $had_flag = true;
  20. break;
  21. }
  22. }
  23. if($had_flag)
  24. {
  25. continue;
  26. }
  27. fsRank(substr($base, 0, $i). substr($base, $i+1, $len-$i-1), $temp.$base[$i]);
  28. }
  29. }
  30. return $ret;
  31. }
  32. print '
    '; </li>
    <li>print_r(fsRank('122'));</li>
    <li>print '
    ';
  33. ?>
Copy code
The recursive algorithm of full arrangement is introduced. Here is a non-recursive algorithm implementation code for full arrangement of PHP arrays. You can refer to it.


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template