如何生成的字符串在PHP的所有排列? [英] How to generate all permutations of a string in PHP?

查看:197
本文介绍了如何生成的字符串在PHP的所有排列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个算法,返回的所有字符所有可能的组合在一个字符串。

I need an algorithm that return all possible combination of all characters in one string.

我已经试过:

$langd = strlen($input);
 for($i = 0;$i < $langd; $i++){
     $tempStrang = NULL;
     $tempStrang .= substr($input, $i, 1);
  for($j = $i+1, $k=0; $k < $langd; $k++, $j++){
   if($j > $langd) $j = 0;
   $tempStrang .= substr($input, $j, 1);
 }
 $myarray[] = $tempStrang;
}

但是,这仅返回相同量的组合作为字符串的长度

But that only returns the same amount combination as the length of the string.

说出 $输入=哎,其结果必然是:哎,惠EYH,EHY,YHE,叶

Say the $input = "hey", the result would be: hey, hye, eyh, ehy, yhe, yeh.

推荐答案

您可以使用回跟踪为基础的方法,系统地生成所有排列:

You can use a back tracking based approach to systematically generate all the permutations:

// function to generate and print all N! permutations of $str. (N = strlen($str)).
function permute($str,$i,$n) {
   if ($i == $n)
       print "$str\n";
   else {
        for ($j = $i; $j < $n; $j++) {
          swap($str,$i,$j);
          permute($str, $i+1, $n);
          swap($str,$i,$j); // backtrack.
       }
   }
}

// function to swap the char at pos $i and $j of $str.
function swap(&$str,$i,$j) {
    $temp = $str[$i];
    $str[$i] = $str[$j];
    $str[$j] = $temp;
}   

$str = "hey";
permute($str,0,strlen($str)); // call the function.

输出:

#php a.php
hey
hye
ehy
eyh
yeh
yhe

这篇关于如何生成的字符串在PHP的所有排列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆