CS61A RECURSION

1.Recursion

(1)Find the base case

(2)Find the recursion

2.The differece of recursion and while statement

using the math example as anology

resursion: f(n) = n*(n-1)*(n-2)*...*2*1

recursion:f(n) = {n*f(n-1); n > 1

                          1 ; n == 0 or n==1

3.Tree recursion

(1)递推关系的寻找关键:即已知n,找出又n到n+1的路径(路径不一定只有一步,即不一定仅调用一次n)

eg.汉诺塔解法

def move_disk(n, from_peg, to_peg):
    printf("move" + str(n) + "from" + str(from_peg) "to" + str(to_prg))
def solve_hanoi(n, from_peg, to_peg):
    if n == 1:
        move_disk(n, from_peg, to_peg)
    else:
        spare_peg = 6 - from_peg - to_peg
        solve_hanoi(n-1, from_peg, spare_peg)
        move_disk(n, from_peg, to_peg)
        solve_hanoi(n-1, spare_peg, to_peg)

(2)递推关系的寻找方法:对n与n+1的划分

Appendix:

from ucb import trace
"trace is used to show the call progress of the function"
@trace
def f(a,b)
    sum = a + b
    return sum

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值