在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);
这些都是实现递归的基本方式,在具体的应用场景中,可以根据需要选择合适的方式来实现递归。