zoukankan      html  css  js  c++  java
  • [算法] 动态规划

    引入

    • 以求解斐波那契数列为例,如何避免递归中的重复计算
      • 记忆化搜索(指数->线性,对于n=40,性能提升100万倍)
     1 #include <iostream>
     2 #include <ctime>
     3 #include <vector>
     4 using namespace std;
     5 
     6 vector<int> memo;
     7 
     8 int num = 0 ; 
     9 
    10 int fib(int n){
    11     
    12     num ++;
    13     
    14     if( n == 0 )
    15         return 0;
    16         
    17     if( n == 1 )
    18         return 1;
    19     
    20     if( memo[n] == -1 )    
    21         memo[n] = fib(n-1) + fib(n-2);
    22         
    23     return memo[n];    
    24 }
    25 
    26 int main(){
    27     
    28     num = 0 ; 
    29     
    30     int n = 40;
    31     memo = vector<int>(n+1,-1);
    32     
    33     time_t startTime = clock();
    34     int res = fib(n);
    35     time_t endTime = clock();
    36      
    37     cout << "fib("<<n<<") = "<<res<<endl;
    38     cout << "time:"<<double(endTime-startTime)/CLOCKS_PER_SEC<<" s"<<endl;
    39     cout << "run function fib() "<<num<<" times."<< endl;
    40     
    41     return 0; 
    42 }
    View Code
      • 自下而上(动态规划)
        • 将原问题拆解成若干子问题,同时保存子问题的答案,使得每个子问题只求解一次,最终获得原问题的答案
    1 int fib2(int n){
    2     vector<int> memo(n+1, -1);
    3     memo[0] = 0;
    4     memo[1] = 1;
    5     for(int i = 2 ; i <= n ; i ++ ){
    6         memo[i] = memo[i-1] + memo[i-2];
    7     }
    8     return memo[n];
    9 }
    View Code

  • 相关阅读:
    MongoDB入门
    查看端口通不通
    jQuery通过name获取值
    thinking in java
    xml配置文件解释
    Spring定时器时间设置规则
    修改序列(Sequence)的初始值(START WITH)
    Go语言实现简单的一个静态WEB服务器
    [转载]XML非法字符的处理
    IIS7解决文件上传大小问题
  • 原文地址:https://www.cnblogs.com/cxc1357/p/12717331.html
Copyright © 2011-2022 走看看