题目:给定整数N, 返回斐波那契数列的第N项
补充问题1:给定整数N,代表台阶数,一次可以跨2个或者1个台阶,返回有多少中走法
补充问题2:假设农场中成熟的母?每年只会省1头小母牛,并且永远不会死。第一年农场有1只成熟的母牛,第二年开始,母牛开始生小母牛。每只小母牛3年之后成熟又可以生小母牛。给定整数N,求出N年后牛的
"""原文题 复杂度O(2^n)"""
def f1(n):
if n < 1:
return 0
if n==1 or n==2:
return 1
return f(n-1) + f(n-2)
"""原问题 复杂度O(N)"""
def f2(n):
if n < 1:
return 0
if n==1 or n==2:
return 1
res = 1
pre = 1
tmp = 0
for i in range(3,n):
tmp = res
res = res + pre
pre = tmp
return res
"""原问题O(logN)"""
def maxtrixPower(m,p):
res = [[0 for i in range(len(m[0]))] for j in range(len(m))]
for i in range(len(res)):
res[i][j] = 1
tmp = m
while p > 0:
if p&1!=0: //p为奇数
res = muliMatrix(res,tmp)
tmp = muliMatrix(tmp,tmp)
p >>= 1
return res
def muliMatrix(m1,m2):
res = [[0 for i in range(len(m2[0]))] for j in range(len(m1))]
for i in range(len(m1)):
for j in range(len(m2[0])):
for k in range(len(m1[0])):
res[i][j] += m1[i][k] * m2[k][j]
return res
def f3(n):
if n < 1:
return 0
if n == 1 or n == 2:
return 1
base = [[1,1],[1,0]]
res = matrixPower(base,n-2)
return res[0][0] + res[1][0]
"""补充问题1"""
def s1(n):
if n < 1:
return 0
if n==1 or n==2:
return n
return s1(n-1) + s1(n-2)
def s2(n):
if n < 1:
return 0
if n == 1 or n==2:
return n
res = 2
pre = 1
tmp = 0
for i in range(3,n):
tmp = res
res = res + pre
pre = tmp
return res
def s3(n):
if n < 1:
return 0
if n==1 or n==2:
return n
base = [[1,1],[1,0]]
res = matrixPower(base,n-2)
return 2*res[0][0] + res[1][0]
"""补充问题2"""
def c1(n):
if n < 1:
return 0
if n==1 or n==2 or n==3:
return n
return c1(n-1) + c1(n-3)
def c2(n):
if n < 1:
return 0
if n==1 or n==2 or n==3:
return n
res = 3
pre = 2
prpre = 1
tmp1 = 0
tmp2 = 0
for i in range(4,n):
tmp1 = res
tmp2 = pre
res = res + pre
pre = tmp1
prpre = tmp2
return res
def c3(n):
if n < 1:
return 0
if n==1 or n==2 or n==3:
return n
base = [[1,1,0],[0,0,1],[1,0,0]]
res = matrixPower(base,n-3)
return 3*res[0][0] + 2*res[1][0] + res[2][0]