php 遞歸函數(shù)的三種實(shí)現(xiàn)方式,php遞歸函數(shù)三種
Jun 13, 2016 am 08:56 AMphp 遞歸函數(shù)的三種實(shí)現(xiàn)方式,php遞歸函數(shù)三種
遞歸函數(shù)是我們常用到的一類(lèi)函數(shù),最基本的特點(diǎn)是函數(shù)自身調(diào)用自身,但必須在調(diào)用自身前有條件判斷,否則無(wú)限無(wú)限調(diào)用下去。實(shí)現(xiàn)遞歸函數(shù)可以采取什么方式呢?本文列出了三種基本方式。理解其原來(lái)需要一定的基礎(chǔ)知識(shí)水品,包括對(duì)全局變量,引用,靜態(tài)變量的理解,也需對(duì)他們的作用范圍有所理解。遞歸函數(shù)也是解決無(wú)限級(jí)分類(lèi)的一個(gè)很好地技巧。如果對(duì)無(wú)限級(jí)分類(lèi)感興趣,請(qǐng)參照php利用遞歸函數(shù)實(shí)現(xiàn)無(wú)限級(jí)分類(lèi)。我習(xí)慣套用通俗的話(huà)解釋復(fù)雜的道理,您確實(shí)不明白請(qǐng)參見(jiàn)手冊(cè)。
利用引用做參數(shù)
先不管引用做不做參數(shù),必須先明白引用到底是什么?引用不過(guò)是指兩個(gè)不同名的變量指向同一塊存儲(chǔ)地址。本來(lái)每個(gè)變量有各自的存儲(chǔ)地址,賦值刪除各行其道?,F(xiàn)在可好,兩個(gè)變量共享一塊存儲(chǔ)地址。?$a=&$b;?。實(shí)際上指的是?$a?不管不顧自己原來(lái)的存儲(chǔ)地址,非要和?$b?共享一室了。因而任何對(duì)存儲(chǔ)地址數(shù)值的改變都會(huì)影響兩個(gè)值?! ?/p>
函數(shù)之間本來(lái)也是各行其是,即便是同名函數(shù)。遞歸函數(shù)是考慮將引用作為參數(shù),成為一個(gè)橋梁,形成兩個(gè)函數(shù)間的數(shù)據(jù)共享。雖然兩個(gè)函數(shù)見(jiàn)貌似操作的是不同地址,但是實(shí)際上操作的是一塊兒內(nèi)存地址。
<span>function</span> test(<span>$a</span>=0,&<span>$result</span>=<span>array</span><span>()){ </span><span>$a</span>++<span>; </span><span>if</span> (<span>$a</span><10<span>) { </span><span>$result</span>[]=<span>$a</span><span>; test(</span><span>$a</span>,<span>$result</span><span>); }<br />echo $a; </span><span>return</span> <span>$result</span><span>; }</span>
上面的例子非常簡(jiǎn)答,以$a<10作為判斷條件,條件成立,則把$a賦給$result[];將$result的引用傳入函數(shù),會(huì)將每一次遞歸產(chǎn)生的$a添加到結(jié)果數(shù)組$result。因而本例生成的$result數(shù)組是 Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 ) 。
本例比較有意思的是echo $a 的值。相信很多人認(rèn)為是12345678910吧,其實(shí)不然,是1098765432。為什么呢?因?yàn)楹瘮?shù)還沒(méi)執(zhí)行echo $a前就進(jìn)行了下一次的函數(shù)遞歸。真正執(zhí)行echo $a是當(dāng)$a<10條件不滿(mǎn)足的時(shí)候,echo $a,返回$result,對(duì)于上一層而言,執(zhí)行完遞歸函數(shù),開(kāi)始執(zhí)行本層的echo $a,依次類(lèi)推。
利用全局變量
利用全局變量完成遞歸函數(shù),請(qǐng)確保你確實(shí)理解什么是全局變量。global在函數(shù)內(nèi)申明變量不過(guò)是外部變量的同名引用。變量的作用范圍仍然在本函數(shù)范圍內(nèi)。改變這些變量的值,外部同名變量的值自然也改變了。但一旦用了&,同名變量不再是同名引用。利用全局變量實(shí)現(xiàn)遞歸函數(shù)沒(méi)必要理解到這么深的一層,還保持原有對(duì)全局變量的看法就可以順理成章理解遞歸函數(shù)。
<span>function</span> test(<span>$a</span>=0,<span>$result</span>=<span>array</span><span>()){ </span><span>global</span> <span>$result</span><span>; </span><span>$a</span>++<span>; </span><span>if</span> (<span>$a</span><10<span>) { </span><span>$result</span>[]=<span>$a</span><span>; test(</span><span>$a,$result</span><span>); } </span><span>return</span> <span>$result</span><span>; }</span>
利用靜態(tài)變量
我們常常在類(lèi)中見(jiàn)到static,今天我們把它利用到遞歸函數(shù)中。請(qǐng)記住static的作用:僅在第一次調(diào)用函數(shù)的時(shí)候?qū)ψ兞窟M(jìn)行初始化,并且保留變量值。
舉個(gè)栗子:
<span>function</span><span> test(){ </span><span>static</span> <span>$count</span>=0<span>; </span><span>echo</span> <span>$count</span><span>; </span><span>$count</span>++<span>; } test(); test(); test(); test(); test();</span>
請(qǐng)問(wèn)這一段代碼的執(zhí)行結(jié)果是多少?是00000么?必然不是。是01234。首先第一次調(diào)用test(),static對(duì) $count 進(jìn)行初始化,其后每一次執(zhí)行完都會(huì)保留 $count 的值,不再進(jìn)行初始化,相當(dāng)于直接忽略了 static $count=0; 這一句。
因而將static應(yīng)用到遞歸函數(shù)作用可想而知。在將需要作為遞歸函數(shù)間作為“橋梁"的變量利用static進(jìn)行初始化,每一次遞歸都會(huì)保留"橋梁變量"的值。
<span>function</span> test(<span>$a</span>=0<span>){ </span><span>static</span> <span>$result</span>=<span>array</span><span>(); </span><span>$a</span>++<span>; </span><span>if</span> (<span>$a</span><10<span>) { </span><span>$result</span>[]=<span>$a</span><span>; test(</span><span>$a</span><span>); } </span><span>return</span> <span>$result</span><span>; }</span>
總結(jié)
所謂遞歸函數(shù),重點(diǎn)是如何處理函數(shù)調(diào)用自身是如何保證所需要的結(jié)果得以在函數(shù)間合理"傳遞",當(dāng)然也有不需要函數(shù)之間傳值得遞歸函數(shù),例如:
<span>function</span> test(<span>$a</span>=0<span>){ </span><span>$a</span>++<span>; </span><span>if</span> (<span>$a</span><10<span>) { </span><span>echo</span> <span>$a</span><span>; test(</span><span>$a</span><span>); } }</span>
面對(duì)這樣的函數(shù),我們就不必大傷腦筋了。順便說(shuō)一句,深入理解變量引用相關(guān)知識(shí)對(duì)解決這類(lèi)問(wèn)題大有裨益。
?

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

To optimize the performance of recursive functions, you can use the following techniques: Use tail recursion: Place recursive calls at the end of the function to avoid recursive overhead. Memoization: Store calculated results to avoid repeated calculations. Divide and conquer method: decompose the problem and solve the sub-problems recursively to improve efficiency.

Python is a very powerful programming language, and many programmers choose Python as their main programming language. However, too much function nesting in the code can make the program difficult to maintain and understand. This article will explore how to solve the excessive function nesting error in Python code. A brief introduction to function nesting Function nesting refers to the process of defining another function in the body of a function. Function nesting can make the structure of the program clearer and the code easier to read and maintain. However, too many nested functions can lead to an overly complex code structure.

The exit conditions of C++ recursive functions include: Baseline conditions: Check whether the function reaches a state that can directly return results, usually judging whether a certain condition or parameter value meets the threshold. Recursion termination condition: Alternative to or in addition to the baseline condition, ensuring that the function stops after a certain number of recursive calls, by tracking the recursion depth or setting a maximum recursion depth limit.

Here we have a directory. Our task is to create a C program to list all files and subdirectories in a directory. A directory is a place/area/location where a set of file(s) will be stored. A subdirectory is a directory within the root directory, which, in turn, can have another subdirectory. In C programming language you can easily list all files and subdirectories in a directory. The following program shows how to list all files and subdirectories in a directory. //C program example to list all files and subdirectories in the directory Live demonstration #include<stdio.h>#include<dirent.h>intmain(void){ &am

In Golang, recursion is a way for a function to call itself. Many problems can be solved using recursive functions, such as calculating factorials, Fibonacci sequences, etc. However, when writing recursive functions, you need to pay attention to some details, otherwise program errors may occur. This article will introduce the details of recursive functions in Golang to help developers write more stable and reliable recursive functions. Handling of basic situations When writing a recursive function, you first need to consider the basic situation, that is, the conditions for the exit of the recursive function. If there is no positive

Recursive functions are used in search algorithms to explore tree-like data structures. Depth-first search uses a stack to explore nodes, while breadth-first search uses a queue to traverse layer by layer. In practical applications, such as finding files, recursive functions can be used to search for a given file in a specified directory.

The tail recursion optimization strategy effectively reduces the function call stack depth and prevents stack overflow by converting tail recursive calls into loops. Optimization strategies include: Detect tail recursion: Check whether there are tail recursive calls in the function. Convert functions into loops: Use loops instead of tail-recursive calls and maintain a stack to save intermediate state.

How to implement factorial using recursive functions in Go language? Factorial is a common calculation in mathematics that multiplies a non-negative integer n by all positive integers smaller than it, up to 1. For example, the factorial of 5 can be expressed as 5!, calculated as 54321=120. In computer programming, we often use recursive functions to implement factorial calculations. First, we need to understand the concept of recursive functions. A recursive function refers to the process of calling the function itself within the definition of the function. When solving a problem, a recursive function will continually
