Home > Backend Development > PHP Tutorial > php用递归实现字符串的全排列?该怎么解决

php用递归实现字符串的全排列?该怎么解决

WBOY
Release: 2016-06-13 12:22:37
Original
1701 people have browsed it

php用递归实现字符串的全排列?
我想在程序中实现打印字符串的全排列,代码如下

<br />function output ($src_arr)<br />{<br />    foreach ($src_arr as $key => $value) {<br />        $temp_arr = $src_arr;<br />        echo $value;<br />        if (! empty($temp_arr)) {<br />            array_splice($temp_arr, $key, 1);<br />            output($temp_arr);<br />            return;<br />        } else {<br />            echo "<br/>";<br />            return;<br />        }<br />    }<br />}<br /><br />$str = 'abc';<br />$src_arr = str_split($str);<br />output($src_arr);
Copy after login



但是结果只是打印abc,我想问一下究竟是什么原因,我感觉没什么问题,请大神指教!
------解决思路----------------------
$a = array(1,2,3);<br />perm($a, 0, count($a)-1);<br /><br />function perm($ar, $k, $m) {<br />  if($k == $m) echo join('',$ar), PHP_EOL;<br />  else {<br />    for($i=$k; $i<=$m; $i++) {<br />      swap($ar[$k], $ar[$i]);<br />      perm($ar, $k+1, $m);<br />    }<br />  }<br />}<br />function swap(&$a, &$b) {<br />  $c = $a;<br />  $a = $b;<br />  $b = $c;<br />}
Copy after login
如果按引用传递原始数组则
$a = array(1,2,3);<br />perm($a, 0, count($a)-1);<br /><br />function perm(&$ar, $k, $m) {<br />  if($k == $m) echo join('',$ar), PHP_EOL;<br />  else {<br />    for($i=$k; $i<=$m; $i++) {<br />      swap($ar[$k], $ar[$i]);<br />      perm($ar, $k+1, $m);<br />      swap($ar[$k], $ar[$i]);<br />    }<br />  }<br />}<br />function swap(&$a, &$b) {<br />  $c = $a;<br />  $a = $b;<br />  $b = $c;<br />}
Copy after login
这个思路要比你的清晰吧?(移植的 C 代码)

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template