Lecture8 Tree Recursion
Reading 1.7
1. Order of Recursive Calls
<1>【eg1】The Cascade Function
>>> def cascade(n):
"""Print a cascade of prefixes of n."""
if n < 10:
print(n)
else:
print(n)
cascade(n//10)
print(n)
>>> cascade(2013)
2013
201
20
2
20
201
2013
<2>【eg2】Inverse Cascade
def inverse_cascade(n): grow(n)
print(n)
shrink(n)
def f_then_g(f, g, n):
if n:
f(n)
g(n)
grow = lambda n: f_then_g(grow, print, n//10) shrink = lambda n: f_then_g(print, shrink, n//10)
>>> inverse_cascade(2013)
1
12
123
1234
123
12
1
2. Tree Recursion
<1>【eg1】Fibonacci numbers
(与树结构进行联系)
n: 0, 1, 2, 3, 4, 5, 6, 7, 8, …,
fib(n): 0, 1, 1, 2, 3, 5, 8, 13, 21,
def fib(n):
if n == 1:
return 0
if n == 2:
return 1
else:
return fib(n-2) + fib(n-1)
result = fib(6)
<2>与树结构的联系
- Repetition in Tree-Recursive Computation
- 【举例】
Counting Partitions
The number of partitions of a positive integer n, using parts up to size m, is the number of ways in which n can be expressed as the sum of positive integer parts up to m in increasing order.
count_partitions(6, 4)
6 = 2 + 4
6 = 1 + 1 + 4
6 = 3 + 3
6 = 1 + 2 + 3
6 = 1 + 1 + 1 + 3
6 = 2 + 2 + 2
6 = 1 + 1 + 2 + 2
6 = 1 + 1 + 1 + 1 + 2
6 = 1 + 1 + 1 + 1 + 1 + 1
解题思路
• Recursive decomposition: finding simpler instances of the problem.
• Explore two possibilities: •Use at least one 4
•Don’t use any 4
• Solve two simpler problems: •count_partitions(2, 4) •count_partitions(6, 3)
• Tree recursion often involves exploring different choices.
所用代码如下:
>>> def count_partitions(n, m):
"""Count the ways to partition n using parts up to m."""
if n == 0:
return 1
elif n < 0:
return 0
elif m == 0:
return 0
else:
return count_partitions(n-m, m) + count_partitions(n, m-1)
>>> count_partitions(6, 4)
9
>>> count_partitions(5, 5)
7
>>> count_partitions(10, 10)
42