斐波那契数列的递归和非递归实现
非递归
#include <iostream> using namespace std; int fib(int n) { if(n < 2) return n < 0 ? 0:n; int cur_2 = 0 , cur_1 = 1 , cur = 0; // 将从2到n的斐波那契数都计算出来,层层累加 for(int i = 2; i <= n; i++) { cur = cur_2 + cur_1; cur_2 = cur_1; cur_1 = cur; } return cur; } int main(int argc, char* argv[]) { for(int i = -1; i < 6; i++) { cout << fib(i) << " "; } cout << endl; return 0; }
递归
int recursiveFib(int n ) { if(n < 2) return n < 0 ? 0 : n; else return recursiveFib(n - 1) + recursiveFib(n - 2); }