#include<iostream> using namespace std; long long int memo[20] = {-1}; //create memo table and initialise to -1 long long int fibo(long long int n) { if(memo[n]>-1) //changing this to if(memo[n]>0) works fine return memo[n]; //but as such this gives 0 from all my inputs if(n<=2) return 1; memo[n] = fibo(n-1) + fibo(n-2); //recurse return memo[n]; } int main() { long long int n; cin>>n; cout<<fibo(n)<<endl; //calls the fibo function for(int i=0;i<20;i++) //this prints my memo table used... cout<<memo[i]<<" "; }
I calculate the nth Fibonacci number using down-down dp, but my note table is reset. Why in places that I donβt touch, why?
Because how array initialization works in C ++. You set the first element of the array memoto -1, and the compiler will be value-initialize (before the C ++ 11 standard) or default-initialize (starting from C ++ 11 onwards) of all other elements.
memo
-1
Read more about aggregate initialization here .
long long int memo[20] = {-1};
-1. , , . , .
long long int memo[20] = {-1}; -1 . 0.
, , , 0, -1 ,
long long memo[20] = {}; /*new C++ standards allow this, note that C doesn't*/
.
-1, {-1}.
{-1}
++ Stroustrup Array Initializer:
, 0 . :int v5[8] = { 1, 2, 3, 4 }; int v5[] = { 1, 2, 3, 4 , 0, 0, 0, 0 };
, 0 . :
int v5[8] = { 1, 2, 3, 4 };
int v5[] = { 1, 2, 3, 4 , 0, 0, 0, 0 };
, long long int memo[20] = {-1}; , .
, memo .
"memo", , ++. - , memo [3] - - "memo + 3", .
, -1.
long long int memo[20] = {[0 ... 20] = -1};
Source: https://habr.com/ru/post/1662637/More articles:Colored unlimited raven chart cells in MATLAB - matlabError using newer version of glibc - linuxDifference between container reload due to survivability issues or due to a stop request - dockerTwitter Future.collect not working at the same time (Scala) - scalaAndroid BindingAdapter execution order? - androidSlow jdbc connection on Macos Sierra - javaAWS Lambda http, where can I find the url? - amazon-web-servicesLaravel 5.3 Eloquent where the proposal for joining a table from the parent model - sqljava.lang.NoSuchMethodError: No static zzb method - androidNoSuchMethodError: No static zzb method - androidAll Articles