C語言斐波那契數列的四種實現方式—遞迴,迭代,陣列,佇列
阿新 • • 發佈:2019-01-31
自部落格園轉載:
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: }