青蛙跳台阶
作者:互联网
基础版
青蛙一次可以跳1级或者2级台阶,问跳到N级有多少种跳法
class Solution:
def jumpFloor(self,n):
if n < 1:
return 0
if n == 1 or n == 2:
return n
a = 1
b = 2
tmp = 1
for i in range(2,n):
tmp = a+b
a = b
b = tmp
return tmp
Solution().jumpFloor(5)
升级版
青蛙一次可以跳1级或者n级台阶,问跳到N级有多少种跳法
class Solution:
def jumpFloor(self,num):
# f(n) = f(n-1) + f(n-2) + ... + f(1)
# f(n-1) = f(n-2) + f(n-3) + ... + f(1)
# f(n) = 2f(n-1)*n
# return pow(2,num - 1)
if num == 1:
return 1
ret = 1
a = 1
for i in range(2,num + 1):
ret = 2 *a
a = ret
return ret
Solution().jumpFloor(4)
标签:tmp,return,jumpFloor,青蛙,ret,Solution,num,台阶 来源: https://www.cnblogs.com/ray-mmss/p/16622632.html