递归大总结之斐波那契

//利用循环的解法,效率高
#include<iostream>
using namespace std;

int facii(int n)
{
	if (n < 0)
	{
		return 0;
	}
	int a[] = { 0, 1 };
	int i = 0, x1 = 0, x2 = 1, x3 = 0;

	if (n<2)
		return a[n];

	for (i = 2; i <= n; i++)
	{
		x3 = x1 + x2;
		x1 = x2;
		x2 = x3;
	}
	return x3;
}

int main()
{
	int n, y;
	cin >> n;
	y = facii(n);
	cout << y << endl;
	system("pause");
}

递归解法

#include<iostream>
using namespace std;
int f(int n)
{
	if (n < 0)
	{
		return 0;
	}
	int arr[2] = { 0, 1 };
	if (n < 2)
	{	
		return arr[n];
	}
	return f(n - 1) + f(n - 2);
}
int main()
{
	int n;
	int res;
	cin >> n;
	res=f(n);
	cout << res << endl;
	system("pause");
}


posted @ 2017-03-07 23:20  乐天的java  阅读(46)  评论(0)    收藏  举报