更高效的Fibonacci求解

两种思想三种方式实现斐波那序列求解,一种是传统递归的思想,一种是动态规划的思想,动态规划又分为Top-down和Bottom-up两种方式。

// Fast_Fibonacci.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <time.h>//support for clock()
using namespace std;

int Fib1(int n)//传统递归方式实现--有每次重复计算值的缺点
{
	if (n <= 0)
		return -1;
	if (n == 1 || n == 2)
		return 1;
	else
		return Fib1(n - 1) + Fib1(n - 2);
}

int F[10] = { 0 };//暂存数组(每位均初始为0),用来判断F[n]是否已定义过
int Fib2(int n)//动态规划思想--高效的Top-down方法--记忆化,不重复计算值
{
	if (n <= 0)
		return -1;
	if (n == 1 || n == 2)
		return 1;
	if (F[n] != 0)//Indicate that F[n] is defined!
		return F[n];
	F[n] = Fib2(n-1) + Fib2(n-2);
	return F[n];
}

int Fib3(int n)//用动态规划的思想求解--Bottom up方法
{
	if (n <= 0)
		return -1;
	if (n == 1 || n == 2)
		return 1;
	F[1] = F[2] = 1;
	for(int i = 3; i <= n; i++)
		F[i] = F[i - 1] + F[i - 2];
	return F[n];
}

int main()
{
	int t1,t2,t3;
	t1 = Fib1(5);
	t2 = Fib2(5);
	t3 = Fib3(5);
	cout << t1 << endl << t2 << endl << t3 << endl;
	////int n = 100000;
	//clock_t start, finish, duration;
	//start = clock();
	//t1 = Fib1(5);
	////while (n--);
	//finish = clock();
	//duration = (double)(finish - start) / CLOCKS_PER_SEC;
	//cout << "方法1--传统方法,耗时秒数:" << duration << endl;

	//start = clock();
	//t2 = Fib2(5);
	//finish = clock();
	//duration = (double)(finish - start) / CLOCKS_PER_SEC;
	//cout << "方法2--Top-down方法,耗时秒数:" << duration << endl;

    return 0;
}

动态规划是个好东西也是个难点。是个非常重要的算法,需要好好学习。

你可能感兴趣的:(fibonacci,斐波那)