-
- 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 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.
- 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 '
'; </li>
<li>print_r(fsRank('122'));</li>
<li>print ' ';
- ?>
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. |