递归

recursion完成了iteration,但逻辑清晰,有以下问题:

  • recursion 由stack完成,会溢出
  • solution: compute argument then input to recursion func

like this, 输入recursion的参数已经计算

return fact_iter(num - 1, num * product)
===> fact_iter(5, 1)
===> fact_iter(4, 5)
===> fact_iter(3, 20)
===> fact_iter(2, 60)
===> fact_iter(1, 120)
===> 120
  • 那现在总体应该写成:
def fact(n): 
    return fact_iter(n, 1)
#
def fact_iter(num, product): 
    if num == 1: 
       return product 
    return fact_iter(num - 1, num * product)

经典汉诺塔

  1. n-1右移到b
  2. 移动第n 回移前n-1
  3. 交换参数位置 变换移动like abc---> acb 带一个bac

你可能感兴趣的:(递归)