PHP full-array Recursive algorithm code

Source: Internet
Author: User
    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 Code

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 logo, problem solving.

    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 '
      ';
    33. Print_r (Fsrank (' 122 '));
    34. print '
    35. ';
    36. ?>
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.
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.