一個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 回答

哆啦的時光機
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 關注
- 537 瀏覽
添加回答
舉報
0/150
提交
取消