在PHP中,實現遞歸的基本方式有以下幾種:
function factorial($n) {
// 遞歸終止條件
if ($n == 0) {
return 1;
}
// 遞歸調用
return $n * factorial($n - 1);
}
$result = [];
function generatePermutations($arr, $n, $current = []) {
global $result;
if ($n == 0) {
$result[] = $current;
return;
}
for ($i = 0; $i < count($arr); $i++) {
$newArr = $arr;
$element = array_splice($newArr, $i, 1)[0];
$newCurrent = array_merge($current, [$element]);
generatePermutations($newArr, $n - 1, $newCurrent);
}
}
$numbers = [1, 2, 3];
generatePermutations($numbers, count($numbers));
print_r($result);
function generatePermutations($arr, $n, $current = [], &$result) {
static $result = [];
if ($n == 0) {
$result[] = $current;
return;
}
for ($i = 0; $i < count($arr); $i++) {
$newArr = $arr;
$element = array_splice($newArr, $i, 1)[0];
$newCurrent = array_merge($current, [$element]);
generatePermutations($newArr, $n - 1, $newCurrent, $result);
}
}
$numbers = [1, 2, 3];
generatePermutations($numbers, count($numbers));
print_r($result);
這些都是實現遞歸的基本方式,在具體的應用場景中,可以根據需要選擇合適的方式來實現遞歸。