跳台阶
时间限制:1秒 空间限制:32768K 热度指数:377293
算法知识视频讲解
题目描述
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。
解析
对于本题,前提只有 一次 1阶或者2阶的跳法。
a.如果两种跳法,1阶或者2阶,那么假定第一次跳的是一阶,那么剩下的是n-1个台阶,跳法是f(n-1);
b.假定第一次跳的是2阶,那么剩下的是n-2个台阶,跳法是f(n-2)
c.由a\b假设可以得出总跳法为: f(n) = f(n-1) + f(n-2)
d.然后通过实际的情况可以得出:只有一阶的时候 f(1) = 1 ,只有两阶的时候可以有 f(2) = 2
e.可以发现最终得出的是一个斐波那契数列:
| 1, (n=1)
f(n) = | 2, (n=2)
| f(n-1)+f(n-2) ,(n>2,n为整数)
代码:python
1. 递归法【得知道,但做题会超时】
fib = lambda n: n if n <= 2 else fib(n - 1) + fib(n - 2)
2.迭代法
# 斐波那契方法|迭代法
def jumpFloor(self, number):
# write code here
a = 1
b = 1
for i in range(number):
a,b = b,a+b
return a
速度:
import time
start = time.clock()
print(jumpFloor(225))
t2 = time.clock()
print("Time used:{:.2e}".format(t2 - start))
# output:
# 76159080909572301618801306271765994056795952743
# time used:1.02e-04
3. 装饰器+递归
def memo(func):
cache = {}
def wrap(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
return wrap
@memo
def fib(i):
if i < 2:
return 1
return fib(i-1) + fib(i-2)
速度:
import time
start = time.clock()
print(fib(225))
t2 = time.clock()
print("Time used:{:.2e}".format(t2 - start))
# output
# 76159080909572301618801306271765994056795952743
# Time used:1.22e-03
update: 2019年09月29日23:02:00
增加了递归+装饰器法
【来自:台阶问题/斐波那契】