php - 如何在 PHP 中生成字符串的所有排列?

标签 php string algorithm combinations permutation

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

我试过了:

$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;
}

但这只会返回与字符串长度相同的数量组合。

$input = "hey",结果会是:hey, hye, eyh, ehy, yhe, yeh

最佳答案

您可以使用基于回溯的方法系统地生成所有排列:

// 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 - 如何在 PHP 中生成字符串的所有排列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2617055/

相关文章:

php - 如何更改目录路径并在 Ubuntu 上的 PHP 运行文件中创建一个空文件

c++ - 是什么让这个桶排序函数变慢了?

php - css中的宽度可以用变量动态选择吗

php - 登录时重定向到不同页面 - php

php - 无法在 Windows 7 上安装 PHPUnit_Invoker

java - 不兼容类型错误 String[]

swift - 无法将类型 'UIImage' 的值转换为 'NSString'

C# 从嵌套的 if 语句返回结果

c++ - 检查它是完全二叉树还是完全二叉树或两者都不是

java - 大数幂运算