对比下两种方法呗:
import time
class Solution1:
def Fibonacci(self, n):
# write code here
if n == 0:
return 0
if n == 1:
return 1
return self.Fibonacci(n-1) + self.Fibonacci(n-2)
class Solution2:
def Fibonacci(self, n):
# write code here
tmp = [0, 1]
if n <= 1:
return tmp[n]
else:
for i in range(2,n+1):
tmp.append(tmp[i-1]+tmp[i-2])
return tmp[n]
t1 = time.time()
A = Solution1()
b = A.Fibonacci(30)
t2 = time.time()
tt1 = t2 - t1
print("时间tt1:",t2 - t1)
t3 = time.time()
A1 = Solution2()
bb = A1.Fibonacci(30)
t4 = time.time()
tt2 = t4-t3
print("时间tt2:",tt2)
print("速度快{}倍".format(tt1/tt2))
结果:
时间tt1: 0.6568622589111328
时间tt2: 1.71661376953125e-05
速度快38265.0倍