阿摩線上測驗 登入

申論題資訊

試卷:113年 - 113 司法特種考試_三等_檢察事務官電子資訊組:程式語言#122108
科目:程式語言
年份:113年
排序:0

題組內容

二、遞迴函式(Recursion)是程式語言常用的解題技巧之一,請回答下列問題:

申論題內容

(四)請修改上述的費式數列遞迴函式版本,使其可以加快執行的時間(接近迴圈的版本) 。(15 分)

詳解 (共 1 筆)

詳解 提供者:hchungw
// 使用迴圈計算第 n 個費氏數列的值(C++ 版本)
#include <iostream>
#include <vector>
using namespace std;
int fibonacci_iterative(int n) {
    if (n <= 0) {
        return 0;
    } else if (n == 1) {
        return 1;
    }
    int a = 0, b = 1;
    for (int i = 2; i <= n; ++i) {
        int temp = b;
        b = a + b;
        a = temp;
    }
    return b;
}
// 使用備忘錄遞迴計算第 n 個費氏數列的值(C++ 版本)
int fibonacci_recursive_helper(int n, vector<int>& memo) {
    if (n <= 0) {
        return 0;
    } else if (n == 1) {
        return 1;
    }
    if (memo[n] != -1) {
        return memo[n];
    }
    memo[n] = fibonacci_recursive_helper(n - 1, memo) + fibonacci_recursive_helper(n - 2, memo);
    return memo[n];
}
int fibonacci_recursive(int n) {
    vector<int> memo(n + 1, -1);
    return fibonacci_recursive_helper(n, memo);
}
int main() {
    int n = 10;
    cout << "Fibonacci Iterative (n=" << n << "): " << fibonacci_iterative(n) << endl;
    cout << "Fibonacci Recursive (with memoization) (n=" << n << "): " << fibonacci_recursive(n) << endl;
    return 0;
}