zoukankan      html  css  js  c++  java
  • 动态规划对比递归----以求斐波那契数列为例

    下面是递归方式:

    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万倍。。。。。。

  • 相关阅读:
    vim编辑器
    linux常用的命令解释
    克隆虚拟机及本地仓库的搭建
    创建windows系统下的虚拟机
    创建linux系统下的虚拟机
    drf频率组件
    django中过滤 搜索 排序
    drf分页
    js回顾
    数据类型
  • 原文地址:https://www.cnblogs.com/LouisGuo/p/4645195.html
Copyright © 2011-2022 走看看