标签:
下面是递归方式:
private static int Fib_RE(int n) { re_Count++; if(n<=1) { return 1; } else { return Fib_RE(n-1) + Fib_RE(n-2); } }
下面是动态规划:
private static int Fib_Fast(int n,Dictionary<int, int> dic) { fa_Count++; if(!dic.ContainsKey(n)) { dic.Add(n, Fib_Fast(n-1,dic)+Fib_Fast(n-2,dic)); } return dic[n]; }
测试过程:
const int NUM = 40; Stopwatch sw = new Stopwatch(); sw.Start(); int result_re = Fib_RE(NUM); sw.Stop(); Console.WriteLine(" Fib_RE({0})={1}: time: {2}, times: {3}", NUM,result_re, sw.ElapsedTicks, re_Count); sw.Reset(); sw.Start(); Dictionary<int, int> dic = new Dictionary<int, int>(); dic.Add(0,1); dic.Add(1,1); int result_fa = Fib_Fast(NUM,dic); sw.Stop(); Console.WriteLine(" Fib_Fast({0})={1}: time: {2}, times: {3}", NUM,result_fa, sw.ElapsedTicks, fa_Count);
结果:
时间将近2万倍。。。。。。
标签:
原文地址:http://www.cnblogs.com/LouisGuo/p/4645195.html