我已经使用递归实现了斐波那契数列:
def fibonacci(n):
if n==0:
return 0
elif n==1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
我还使用动态编程来实现它:
def fibonacci(n):
result = [0, 1]
if n > 1:
for i in range(2, n+1):
result.append(result[i-1] + result[i-2])
return result[n]
我想用贪婪的方法来实现它。我无法从贪婪的角度来考虑它。请为这个问题提供一个贪婪的方法。
答案 0 :(得分:1)
我不明白您想说“贪心”一词的意思。但是这些方法是:
def fib(n):
a,b = 1,1
for i in range(n-1):
a,b = b,a+b
return a
print fib(5)
def fibR(n):
if n==1 or n==2:
return 1
return fibR(n-1)+fibR(n-2)
print fibR(5)
a,b = 0,1
def fibI():
global a,b
while True:
a,b = b, a+b
yield a
f=fibI()
f.next()
f.next()
f.next()
f.next()
print f.next()
def memoize(fn, arg):
memo = {}
if arg not in memo:
memo[arg] = fn(arg)
return memo[arg]
fibm = memoize(fib,5)
print fibm
class Memoize:
def __init__(self, fn):
self.fn = fn
self.memo = {}
def __call__(self, arg):
if arg not in self.memo:
self.memo[arg] = self.fn(arg)
return self.memo[arg]
@Memoize
def fib(n):
a,b = 1,1
for i in range(n-1):
a,b = b,a+b
return a
print fib(5)