[PHP] 算法-字符串的全排列的PHP实现

输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。 
思路:
1.利用递归形成递归树,达到深度优先,固定首字母的效果
2.得复位以后才能再次深度优先
3.回溯法思想
4.一张图和一个运行过程,只能慢慢体会了
<?php
function 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"
}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券