一个php的全排列函数
function getAll($array,$str=null){
$length = count($array);
if($length<=1){
echo $str.$array[0].PHP_EOL;
}else{
for($i=0;$i<$length;$i++){
$temp = $array;
array_splice($temp,$i,1);
//print_r($temp);
getAll($temp,$str.$array[$i]);
}
}
}
$array = [a,b,c]输出abcacbbacbcacabcba是正确的.但是
function getAll2($array,$str=null){
$length = count($array);
if($length<=1){
echo $str.$array[0].PHP_EOL;
}else{
for($i=0;$i<$length;$i++){
$temp = $array;
array_splice($temp,$i,1);
$str =$str.$array[$i];
getAll2($temp,$str);
}
}
}
仅仅变化了一点点,$str =$str.$array[$i];getAll2($temp,$str); 换了一下传递参数的方法,整个输出就变了.请问能解释一下问什么吗?
1 回答
![?](http://img1.sycdn.imooc.com/5458477300014deb02200220-100-100.jpg)
哆啦的时光机
TA贡献1779条经验 获得超6个赞
因为在getAll2中. for循环里面:
$str =$str.$array[$i];
你对str进行了重新赋值,而第一个str没有被重新赋值,只是单纯拼了个新的传进去.
把第二个改成这样也是正常的:
function getAll2($array,$str=null){
$length = count($array);
if($length<=1){
echo $str.$array[0].PHP_EOL;
}else{
for($i=0;$i<$length;$i++){
$temp = $array;
array_splice($temp,$i,1);
$str2 =$str.$array[$i];
getAll2($temp,$str2);
}
}
}
- 1 回答
- 0 关注
- 519 浏览
添加回答
举报
0/150
提交
取消