定義:F(0)=0, F(1)=1, F(n)=F(n-1)+F(n-2)。
int fibonacci(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
return fibonacci(n-1) + fibonacci(n-2);
}
缺點:遞歸樹指數級重複計算,時間 O(2^n)。實際工程用迭代/矩陣快速冪/備忘錄優化至 O(n) 或 O(log n)。
規則:三根柱 A、B、C。將 N 個盤子從 A 移至 C,借助 B。每次移一盤,大盤不得置於小盤上。
參數順序:hanoi(n, from, aux, to)。
void hanoi(int n, int from, int aux, int to) {
if (n == 1) {
printf("%d -> %d\n", from, to);
return;
}
hanoi(n-1, from, to, aux); // 步驟1
printf("%d -> %d\n", from, to); // 步驟2
hanoi(n-1, aux, from, to); // 步驟3
}
1 -> 3
1 -> 2
3 -> 2
1 -> 3
2 -> 1
2 -> 3
1 -> 3
共 15 步(2^4-1),輸出略。
2^n - 1。2^(n+1) - 1(含葉子節點打印)。#include <stdio.h>
int fibonacci(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
return fibonacci(n-1) + fibonacci(n-2);
}
void hanoi(int n, int from, int aux, int to) {
if (n == 1) { printf("%d -> %d\n", from, to); return; }
hanoi(n-1, from, to, aux);
printf("%d -> %d\n", from, to);
hanoi(n-1, aux, from, to);
}
int main() {
printf("Fibonacci(8) = %d\n", fibonacci(8)); // 21
printf("\nHanoi 3 disks:\n");
hanoi(3, 1, 2, 3);
return 0;
}