您的位置:首页 > 编程语言 > C语言/C++

C语言斐波那契数列的四种实现方式—递归,迭代,数组,队列

2016-12-06 00:25 726 查看
自博客园转载:

1.递归

效率低,除了最后一个数,每个数都被重复计算若干次

1: //递归实现
2: public static int Fib1(int n)
3: {
4: if (n < 3)
5: {
6: return 1;
7: }
8: else
9: {
10: return Fib1(n - 1) + Fib1(n - 2);
11: }
12: }

2.迭代

效率最高,时间复杂度O(n),空间复杂度是O(1)
1: //迭代实现
2: public static int Fib2(int n)
3: {
4:     if (n < 3)
5:     {
6:         return 1;
7:     }
8:     else
9:     {
10:         int first = 1;
11:         int second = 1;
12:         int temp = 0;
13:
14:         for (int i = 0; i < n - 2; i++)
15:         {
16:             temp = first + second;
17:             first = second;
18:             second = temp;
19:         }
20:         return temp;
21:     }
22: }


3.数组

效率一般,比递归快,时间复杂度O(n),空间复杂度是O(n)
1: //数组实现
2: public static int Fib3(int n)
3: {
4:     List<int> list = new List<int>();
5:     list.Add(1);
6:     list.Add(1);
7:     int count = list.Count;
8:
9:     while (count < n)
10:     {
11:         list.Add(list[count - 2] + list[count - 1]);
12:         count = list.Count;
13:     }
14:
15:     return list[count - 1];
16: }
 

4.队列

时间复杂度O(n),空间复杂度是O(1)
1: //队列实现
2: public static int Fib4(int n)
3: {
4:     Queue<int> queue = new Queue<int>();
5:     queue.Enqueue(1);
6:     queue.Enqueue(1);
7:
8:     for (int i = 0; i <= n - 2; i++)
9:     {
10:         queue.Enqueue(queue.AsQueryable().First() + queue.AsQueryable().Last());
11:         queue.Dequeue();
12:     }
13:     return queue.Peek();
14: }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C 斐波那契