数据结构与算法之递归
一、递归原理
- 递归的两个特点:
1)调用自身;
2)结束条件。
def func3(x):
if x>0:
print(x)
func3(x-1)
#结果:3 2 1
def func4(x):
if x>0:
func4(x-1)
print(x)
#结果:1 2 3
二、递归实例
2.1 实例1-汉诺塔问题
- 问题简化:
n
=
2
n=2
n=2时,将A柱子上的圆盘移动到C柱子上;
1)首先将小圆盘从A移动到B;
2)将大圆盘从A移动到C;
3)将小圆盘从B移动到C;
-
n
n
n个盘子时:
1)将n-1个盘子从A经过C移动到B;
2)将第n个盘子从A移动到C;
3)把n-1个盘子从B经过A移动到C;
def hanoi(n,a,b,c):
if n>0:
hanoi(n-1,a,c,b)
print('moving from {} to {}'.format(a,c))
hanoi(n-1,b,a,c)
hanoi(3,'A','B','C')
#结果
"""
moving from A to C
moving from A to B
moving from C to B
moving from A to C
moving from B to A
moving from B to C
moving from A to C
"""
hanoi(2,'A','B','C')
"""
moving from A to B
moving from A to C
moving from B to C
"""