遞歸
遞歸起源:
- 從前有座山
- 山裏有個廟
- 廟裏有個老和尚講故事
- 講的故事是什麼呢?
- 從前有座山
- …
《盜夢空間》裏的夢也是遞歸的例子,強烈建議觀看這部電影。
代碼例子:
計算
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,...)