---
title: "面试题 （斐波那契数列，复杂度为线性）"
author: "J2EE大鸟"
date: "2014-04-03T21:36:19Z"
tags: []
categories: ["行业应用"]
slug: "untitled"
draft: false
lastmod: "2014-04-03T21:36:19Z"
id: 2040859
url: "https://benworld.iteye.com/blog/2040859"
---

来自网易的一道看似简单的笔试题

题目：要求以线性时间复杂度实现斐波那契数列。

1， 1， 2， 3， 5， 8， 13， 21， 34， 55， 89， 。。。。。。

 

众所周知的斐波那契实现方式为递归实现：

```
int feb1(int n) {
	t1++;
	if(n == 0 || n == 1) return 1;
	return feb1(n-1) + feb1(n-2);
}
```

当n=25时， 迭代次数为242785 。

关于其复杂度的解释比较麻烦，详见[http://www.cnblogs.com/python27/archive/2011/12/09/2282486.html](http://www.cnblogs.com/python27/archive/2011/12/09/2282486.html)

![](http://dl2.iteye.com/upload/attachment/0095/6879/ac565e86-6cbb-3d52-8412-2c556a989bd6.png)

至今看了公开课视频后，才有所感悟，采用动态规划后，其复杂度直接下降到线性，迭代次数为49 。

![](http://dl2.iteye.com/upload/attachment/0095/6881/329301c0-33ad-3148-b690-cf0481ecdde0.png)  
 

```
int a[1000] = {0};
int feb2(int n) {
	t2++;
	if(n == 0 || n == 1) return 1;
	if(a[n] != 0) return a[n];
	else a[n] = feb2(n-1) + feb2(n-2);
	return a[n];
}
```