# approach one(利用递归的思想) 时间复杂度O(2^N)
def total_paths(N):
if N<1:
return 0
if N==1:
return 1;
if N==2:
return 2;
# 递归 F(n) = F(n-1) + F(n-2)
return total_paths(N-1)+total_paths(N-2)
print(total_paths(10))
#approach two 时间复杂度O(N),空间复杂度O(N)
def total_paths(N):
dict = {}
if N<1:
return 0
if N==1:
return 1
if N==2:
return 2
# 备忘录算法,这里利用字典的key:value进行存储
if N in dict.keys():
# 获取字典value
return dict.get(N)
else:
value = total_paths(N-1) + total_paths(N-2)
# 存入字典数据key:value
dict[N] = value
return value
print(total_paths(10))
#approach three(DP,Dynamic ) 时间复杂度O(N),空间复杂度O(1)
def total_paths(N):
if N<1:
return 0
if N==1:
return 1
if N==2:
return 2
a, b = 1, 2
for i in range(3, N+1):
value = a + b
a, b = b, value
return value
print(total_paths(10))