函數(shù)遞歸原理:函數(shù)調(diào)用自身(自引用)。每次調(diào)用參數(shù)變化。持續(xù)遞歸,直至滿足遞歸條件(停止條件)。函數(shù)遞歸應(yīng)用:簡化復雜問題(分解成子問題)。簡潔代碼(更優(yōu)雅)。案例:計算階乘(分解為乘積)。查找樹中節(jié)點的祖先(遍歷遞歸尋找)。
PHP 函數(shù)遞歸調(diào)用的原理和應(yīng)用
什么是函數(shù)遞歸
函數(shù)遞歸是指函數(shù)在調(diào)用自身的一種自引用特性。當一個函數(shù)在自身內(nèi)部調(diào)用時,稱之為遞歸調(diào)用。
遞歸的原理
-
函數(shù)調(diào)用自身。
在遞歸調(diào)用中,函數(shù)的參數(shù)會發(fā)生變化。
遞歸過程會持續(xù)進行,直到達到遞歸條件。
遞歸條件滿足后,函數(shù)會停止遞歸,返回結(jié)果。
遞歸的優(yōu)勢
解決復雜問題:遞歸可以將復雜的問題分解成更小的子問題,從而簡化解決方案。
代碼簡潔:遞歸代碼通常比非遞歸代碼更簡潔、優(yōu)雅。
應(yīng)用案例
1. 計算階乘
function factorial($number) {
if ($number == 1) {
return 1;
} else {
return $number * factorial($number - 1);
}
}
echo factorial(5); // 輸出: 120
登錄后復制
2. 尋找樹中節(jié)點的祖先
class Node {
public $data;
public $children;
}
function findAncestors($node, $target) {
if ($node->data == $target) {
return [$node->data];
} else {
$ancestors = [];
foreach ($node->children as $child) {
$ancestors = array_merge($ancestors, findAncestors($child, $target));
}
if (!empty($ancestors)) {
$ancestors[] = $node->data;
}
return $ancestors;
}
}
$root = new Node(['data' => 'root']);
$node1 = new Node(['data' => 'node1']);
$node2 = new Node(['data' => 'node2']);
$node3 = new Node(['data' => 'node3']);
$root->children = [$node1, $node2];
$node2->children = [$node3];
$ancestors = findAncestors($root, 'node3');
var_dump($ancestors); // 輸出: ['root', 'node2', 'node3']
登錄后復制






