Last active
April 13, 2017 22:11
-
-
Save SergeyNarozhny/e31afe9f42ef9f81584d2746d26cb98f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cassert> | |
#include <iostream> | |
#include <unordered_map> | |
class Fibonacci final { | |
public: | |
static int get(int n) { | |
assert(n >= 0); | |
if (n == 0 || n == 1) { | |
return n; | |
} | |
static std::unordered_map<int, int> cache; | |
auto &result = cache[n]; | |
if (result == 0) { | |
result = get(n-2) + get(n-1); | |
} | |
return result; | |
} | |
} | |
int main() { | |
int n; | |
std::cin >> n; | |
stf::cout << Fibonacci.get(n) << std::endl; | |
return 0; | |
} |
Or using vector:
static std::vector<int> cache; cache.resize(n+1); ...
Or using only two prev calculated numbers:
int prev = 0; int cur = 1; for (int i = 2; i <= n; i++) { int new_cur = prev + cur; prev = cur; cur = new_cur; } return cur;
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Or using loop:
assert(n >= 0); static std::unordered_map<int, int> cache; cache[0] = 0; cache[1] = 1; for (int i = 2; i <= n; i++) { cache[i] = cache[i - 2] + cache[i - 1]; } return cache[n];