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