问题
一栋楼有N阶楼梯,兔子每次可以跳1、2或3阶,问一共有多少种走法?
思路
如果楼梯只有一个台阶,及n=1,则只有1种方式,及一步走一个台阶
如果楼梯有2个台阶,及n=2,则有2种方式,及((1,1),(2))
如果楼梯有3个台阶,及n=3,则有4种方式,及((1,1,1),(1,2),(2,1),(3))
代码
# 递归方式
def f(n):
'''
:param stairs:the numbers of stair,楼梯的阶数N
:return:
'''
# 判断输入的n参数是否合法
# n是台阶总数
if isinstance(n, int) and n > 0:
# 定义一个字典,其中的key是一步可以走的台阶数,value是对应的可以完成的方式总数
# 可以知道,如果n是1,则只有一种走法,如果n是2,则有2种走法。如果n是3,则有4种走法。
# 如果不在这个字典中,则使用递归
temp_dict = {1:1, 2:2, 3:4}
# 如果n
if n in basic_num.keys():
return temp_dict[n]
else:
return f(n-1) + f(n-2) + f(n-3)
else:
# 输入的楼梯的阶数错误,比如不是整数,或者<=0
print( 'the num of stair is wrong' )
return False