递归
递归起源:
- 从前有座山
- 山里有个庙
- 庙里有个老和尚讲故事
- 讲的故事是什么呢?
- 从前有座山
- …
《盗梦空间》里的梦也是递归的例子,强烈建议观看这部电影。
代码例子:
计算
n
!
{n!}
n!
n
!
=
1
∗
2
∗
3
∗
.
.
.
∗
n
{n!=1*2*3*...*n}
n!=1∗2∗3∗...∗n
def Factorial(n):
if n<=1:
return 1
return n * Factorial(n-1)
factorial(6)
6 * factorial(5)
6 * (5 * factorial(4))
6 * (5 * (4 * factorial(3)))
6 * (5 * (4 * (3 * factorial(2))))
6 * (5 * (4 * (3 * (2 * factorial(1)))))
6 * (5 * (4 * (3 * (2 * 1))))
6 * (5 * (4 * (3 * 2)))
6 * (5 * (4 * 6))
6 * (5 * 24)
6 * 120
720
福利来啦!递归模板:
def recursion(level, param1, param2, ...):
# recursion terminator
if level > MAX_LEVEL:
print_result
return
#process logic in current level
process_data(level, data...)
# drill down
self.recursion(level + 1, p1, ...)
# reverse the current level status if needed
reverse_status(level)
斐波那契数列
def fib(n):
# 最简单的写法:return n if n<=1 else fib(n-1)+fib(n-2)
if n ==0 or n == 1:
return n
return fib(n - 1) + fib(n - 2)
想象一下斐波那契数列的求解树,对应着盗梦空间的多少层“梦境”
================================================
分治
分治法能应用的前提是子问题或不相干,没有中间状态。
代码模板
def divide_conquer(problem, param1, param2,...):
# recursion terminator
if problem is None:
print_result
return
# process data
data = prepare_data(problem)
subproblems = split_problem(problem, data)
# conquer subproblems
subresult1 = self.divide_conquer(subproblems[0], p1,...)
subresult2 = self.divide_conquer(subproblems[1], p1,...)
subresult3 = self.divide_conquer(subproblems[2], p1,...)
...
# process and generate the final result
result = process_result(subresult1, subresult2, subresult3,...)