The main content of this article is about using PHP to realize the full arrangement of strings. It has certain reference value. Interested friends can learn about it.
Input a string and print out all the permutations of characters in the string in dictionary order.
For example, if you input the string abc, all strings abc, acb, bac, bca, cab and cba that can be arranged by the characters a, b, c will be printed.
Ideas:
1. Use recursion to form a recursive tree to achieve the effect of depth priority and fixing the first letter
2. Depth priority can only be resumed after resetting
3. Backtracking method Thought
4. A picture and a running process can only be understood slowly
<?phpfunction test($str,$start,&$res){ //递归终止条件 if($start==strlen($str)){ $res[]=$str; return; } // for($i=$start;$i<strlen($str);++$i){ if($i==$start || $str{$i}!=$str{$start}){ swap($str,$i,$start);var_dump($str.'==='.$start);var_dump($res);sleep(1); test($str,$start+1,$res); swap($str,$i,$start); } } return $res; }function swap(&$str,$a,$b){ if(!is_string($str)) return; $t=$str{$a}; $str{$a}=$str{$b}; $str{$b}=$t; }$str="abc";$res=array();//调用入口,从索引0开始 $res=test($str,0,$res); var_dump($res);
string(7) "abc===0"array(0) { }string(7) "abc===1"array(0) { }string(7) "abc===2"array(0) { }string(7) "acb===1"array(1) { [0]=> string(3) "abc"}string(7) "acb===2"array(1) { [0]=> string(3) "abc"}string(7) "bac===0"array(2) { [0]=> string(3) "abc" [1]=> string(3) "acb"}string(7) "bac===1"array(2) { [0]=> string(3) "abc" [1]=> string(3) "acb"}string(7) "bac===2"array(2) { [0]=> string(3) "abc" [1]=> string(3) "acb"}string(7) "bca===1"array(3) { [0]=> string(3) "abc" [1]=> string(3) "acb" [2]=> string(3) "bac"}string(7) "bca===2"array(3) { [0]=> string(3) "abc" [1]=> string(3) "acb" [2]=> string(3) "bac"}string(7) "cba===0"array(4) { [0]=> string(3) "abc" [1]=> string(3) "acb" [2]=> string(3) "bac" [3]=> string(3) "bca"}string(7) "cba===1"array(4) { [0]=> string(3) "abc" [1]=> string(3) "acb" [2]=> string(3) "bac" [3]=> string(3) "bca"}string(7) "cba===2"array(4) { [0]=> string(3) "abc" [1]=> string(3) "acb" [2]=> string(3) "bac" [3]=> string(3) "bca"}string(7) "cab===1"array(5) { [0]=> string(3) "abc" [1]=> string(3) "acb" [2]=> string(3) "bac" [3]=> string(3) "bca" [4]=> string(3) "cba"}string(7) "cab===2"array(5) { [0]=> string(3) "abc" [1]=> string(3) "acb" [2]=> string(3) "bac" [3]=> string(3) "bca" [4]=> string(3) "cba"}array(6) { [0]=> string(3) "abc" [1]=> string(3) "acb" [2]=> string(3) "bac" [3]=> string(3) "bca" [4]=> string(3) "cba" [5]=> string(3) "cab"}
The above is the detailed content of [PHP Learning] How to achieve full arrangement of strings. For more information, please follow other related articles on the PHP Chinese website!