# MaoBisheng

Asp.Net(C#) & SQL & Oracle

 博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

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.迭代

   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.数组

   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.队列

   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: }
posted on 2012-04-13 17:52  MaoBisheng  阅读(2783)  评论(0编辑  收藏  举报