I am trying to implement an approach using memoization for calculating the nth Fibonacci number.
#include <iostream>
#include <vector>
using namespace std;
int fib(int n, vector<int> v) {
int result = 0;
if (v[n] != 0) {
return v[n];
}
if (n == 1 || n == 2) {
result = 1;
}
else {
result = fib(n - 1, v) + fib(n - 2, v);
}
v[n] = result;
return result;
}
int main()
{
int n = 12;
vector<int> v(n + 1, 0);
cout << fib(n, v);
}
However, I get this error.
runtime error: addition of unsigned offset to 0x602000000110 overflowed to 0x60200000010c (stl_vector.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:34
How do I change the solution to resolve this problem? Thanks!
v.