递推算法和递归算法

#include<iostream>
using namespace std;

int fab(int n)
{
	if (n == 1 || n == 2)
	{
		return 1;
	} else {
		return fab(n - 2) + fab(n - 1);
	}
	
}

int fab2 (int n)
{
	int a[20];
	a[1] = 1;
	a[2] = 1;
	for (int i = 3; i <= n; i++)
	{
		a[i] = a[i-2] + a[i-1];
	}
	return a[n];
}

int main()
{	
	for (int i = 1; i < 20; i++)
	{
		cout << fab (i) << endl;
	}
	cout << endl;
	for (int i = 1; i < 20; i++)
	{
		cout << fab2 (i) << endl;
	}
	return 0;
}
 

 

    原文作者:递归算法
    原文地址: https://blog.csdn.net/juxq/article/details/82924418
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞