Php full-arrangement recursive algorithm code

Source: Internet
Author: User

Algorithm principle

If P is used to represent the full arrangement of n elements, and Pi is used to represent the full arrangement of n elements that do not contain element I, (I) pi indicates the arrangement of Pi with the prefix I. The full arrangement of n elements can be recursively defined:
① If n = 1, P is arranged with only one element I;
② If n> 1, the fully arranged P is composed of the arrangement (I) Pi;
According to the definition, we can see that if you have generated an arrangement Pi for (k-1) elements, then the arrangement of k elements can be generated by adding element I before each Pi.
Code Implementation Copy codeCode: 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 ('20140901 ');

However, after multiple tests, we found that there was a problem: if the same element exists, there would be duplicates in the full arrangement.
For example, there are only three conditions for the full arrangement of '20160301': '20160301', '20160301', and '20160301'. The above method is repeated.
Slightly modified and added a flag to identify duplicates to solve the problem (the Code is as follows ):Copy codeThe 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> ';
Print_r (fsRank ('20140901 '));
Print '</pre> ';

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.