递归-Recursion

递归(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:递归占用太大内存

  • 转为循环

  • 使用尾递归

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值