码迷,mamicode.com
首页 > 其他好文 > 详细

动态规划对比递归----以求斐波那契数列为例

时间:2015-07-14 15:01:21      阅读:94      评论:0      收藏:0      [点我收藏+]

标签:

下面是递归方式:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!