以爬楼梯为例,每次只能爬一个台阶或两个台阶,爬上n个台阶有多少种爬法。
方法一:
def walk(input):
if input == 1:
return 1
if input == 2:
return 2
return walk(input - 1) + walk(input - 2)
上述方法存在多次函数调用及重复计算可以用一下的方式进行改进
方法二:
def walk2(input):
if input == 1:
return 1
if input == 2:
return 2
first = 1
second = 2
third = 0
for _ in range(3, input+1):
third = first + second
first = second
second = third
return second