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> ';