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: }
作者:MaoBisheng
出处:http://maobisheng.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://maobisheng.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。