Advertisement
Guest User

Memoization Using map

a guest
Jun 29th, 2013
331
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.47 KB | None | 0 0
  1. #include <iostream>
  2. #include <map>
  3.  
  4. using namespace std;
  5.  
  6. map<int, int> fibo;
  7.  
  8. int fibonacci( int n )
  9. {
  10. if ( n == 0 || n == 1 ){ return 1; }
  11.  
  12. map<int,int>::iterator itr = fibo.find( n );
  13.  
  14. if ( itr != fibo.end() )
  15. return itr->second;
  16. else
  17. return fibo[ n ] = fibonacci( n -1 ) + fibonacci( n - 2 );
  18. }
  19. int main()
  20. {
  21. int n;
  22. while(cin>>n)
  23. {
  24. cout<<fibonacci(n)<<endl;
  25. }return 0;
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement