-2

可能重复:
如何在 PHP 中生成字符串的所有排列?

我想在 php 中创建一个脚本来接受这个输入:

12a

并输出如下结果:

1, 2, a, 12, 1a, 21, 2a, a1, a2, 12a, 1a2, 21a, 2a1.

我做了一些研究,但我找不到任何可以做到这一点的脚本。

4

2 回答 2

2

这是答案的修改后的功能

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 = "12a";
$len = strlen($str);
for($i =0; $i <= $len; $i++) {
   permute($str,0,$i + 1); // call the function.
}
于 2012-04-27T22:17:02.747 回答
1

这并不完美,因为您的输出集没有明确定义。首先,弄清楚你的输出集应该是什么样子,然后使用下面的方法开始。

<?php

$input = "12a";
$input_array = str_split($input, 1);//get an array of each individual character

$max_length = strlen($input);
$length = 01;
$result = array();

foreach($input_array as $character) {
  $result[] = $character;
}

while ($length < $max_length){
  foreach($result as $substring) {
    foreach($input_array as $character) {
      $result[] = $substring.$character;
    }
  }
  $length++;
}

foreach ($result as $result_string) {
  echo $result_string.", ";
}

请注意,通常这些算法使用“动态编程”。

于 2012-04-27T22:11:10.013 回答