#include #include #include using namespace std; class Fib { // This is step 2 of dynamic programming: Add a cache. public: long long find_fib(int n); vector cache; }; long long Fib::find_fib(int n) // Create the cache if this is the first call. { // Otherwise, return the answer from the cache if it's there. if (cache.size() == 0) cache.resize(n+1, -1); if (cache[n] != -1) return cache[n]; if (n == 0 || n == 1) { // If it's not in the cache, do the recursion, and put cache[n] = 1; // the answer into the cache before returning. } else { cache[n] = find_fib(n-1) + find_fib(n-2); } return cache[n]; } int main(int argc, char **argv) { Fib f; if (argc != 2) { cerr << "usage: fib n\n"; exit(1); } cout << f.find_fib(atoi(argv[1])) << endl; return 0; }