题目
The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,
F(0) = 0, F(1) = 1
F(N) = F(N - 1) + F(N - 2), for N > 1.
Given N, calculate F(N).
Example 1:
Input: 2
Output: 1
Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
Example 2:
Input: 3
Output: 2
Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
Example 3:
Input: 4
Output: 3
Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
Note:
0 ≤ N ≤ 30.
暴力递归
直接通过表达式计算。
class Solution(object):
def fib(self, N):
"""
:type N: int
:rtype: int
"""
if N == 0:
return 0
if N == 1:
return 1
return self.fib(N-1)+self.fib(N-2)
时间复杂度O(2 ^ N),空间复杂度O(2 ^ N).
迭代递归
要计算fib(N),可以先取得fib(N-1)、fib(N-2)的结果,依此类推下去。
class Solution(object):
def fib(self, N):
"""
:type N: int
:rtype: int
"""
if N<1:
return 0
res = [0]*(N+1)
return self.helper(res,N)
def helper(self,res,N):
if N<1:
return 0
if N == 1:
return 1
if res[N]!=0:
return res[N]
res[N] = self.helper(res,N-1)+self.helper(res,N-2)
return res[N]
时间复杂度O(N),空间复杂度O(N).
动态规划
依次计算fib(2),fib(3),fib(4),…,fib(N)。
if N<=1:
return N
res = [0 for i in range(N+1)]
res[0] = 0
res[1] = 1
for i in range(2,N+1):
res[i] = res[i-1]+res[i-2]
return res[N]
时间复杂度O(N),空间复杂度O(N).
优化算法
因为只需要用到前面两个数,直接更换状态就行。
class Solution(object):
def fib(self, N):
"""
:type N: int
:rtype: int
"""
if N<1:
return 0
if N==1:
return 1
pre = 0
cur = 1
for i in range(2,N+1):
ssum = pre + cur
pre = cur
cur = ssum
return ssum
时间复杂度O(N),空间复杂度O(1).