递归-Recursion

xiaoxiao2025-10-31  6

递归(recursion)

WIKI

Recursion in computer science is a method where the solution to a problem depends on solutions to smaller instances of the same problem (as opposed to iteration).

示例:找钥匙

方法一:While循环,只要盒子堆不空,就从中去一个盒子,并在其中仔细查找

Step1:创建一个要查找的盒子堆

Step2:从盒子堆取出一个盒子,在里面找

Step3:如果找到的是盒子,就将其加入盒子堆中,以便以后查找

Step4:如果找到钥匙,则大功告成

Step5:回到第二步

方法二:递归,函数调用自己

Step1:检查盒子中的每样东西

Step2:如果是盒子,就回到第一步

Step3:如果是钥匙,就大功告成

示例:输出1,2,3,4,5

循环:性能更高

def display(n):     for i in range(1, n + 1):         print i

递归:更容易理解

def display(n):     if n == 0:         return     display(n - 1)     print n

>>>

1

2

3

4

5

基线条件(base case)和递归条件(recursive case)

基线条件指函数不再调用自己

递归条件指函数调用自己

def display(n):     if n == 0:  #基线条件         return     display(n - 1)  #递归条件     print n

栈(stack)

栈是限定仅在表头进行插入和删除操作的线性表。

WIKI

In computer science, a stack is an abstract data type that serves as a collection of elements, with two principal operations:

push, which adds an element to the collection, and

pop, which removes the most recently added element that was not yet removed.

定义

栈是一种后进先出的数据结构。

递归调用栈

def fact(x):     if x == 1:         return 1     else:         return x * fact(x - 1)

a = fact(3)

PS:递归占用太大内存

转为循环

使用尾递归

 

转载请注明原文地址: https://www.6miu.com/read-5038816.html

最新回复(0)