Fibonacci number (memory search

Title
11235813213455
n-th term is equal to (n-1) + (n -2).

Code

#include<bits/stdc++.h>
using namespace std;
int fib[1000005];
int dfs(int n){
 if(fib[n])
  return fib[n];
 if(n==1||n==2)
  fib[n]=1;
 else
  fib[n]=(dfs(n-1)+dfs(n-2));
 return fib[n];
}
int main(){
 int n;
 while(cin>>n){
  dfs(n);
  cout<<fib[n]<<endl;
 }
 return 0;
} 

Thinking
using fib save array has been calculated data taken directly when needed, you do not need to waste time calculation is repeated again.

Published 17 original articles · won praise 1 · views 350

Guess you like

Origin blog.csdn.net/weixin_46396354/article/details/104972738