问题
long int F(int n){
long int F[n];
if (n<2) return n;
else {
F[0]=0; F[1]=1;
for (int i=2; i<n+1; i++)
F[i]=F[i-1]+F[i-2];
return F[n]; }
}
Hi guys, can anyone know how to compute the time complexity of the function above? I am studying C++ and I am quite suffering about compute time complexity of a random algorithm. Please help me! Thanks in advance.
回答1:
The code shown relies on a g++ language extension, variable length arrays.
I.e. it's not standard C++.
The code also misdirects a little by using the name F
for two different things.
And do note that the code exhibits Undefined Behavior by indexing an array beyond its end.
Apart from that it's trivial.
When the code is corrected, or is viewed as just pseudo-code, doing n-1 operations has complexity O(n).
回答2:
For this program , complexity is O(n)
回答3:
Since the algorithm is using memoization, time and space complexity is linear O(n).
Usually time complexity involves accounting comparison operations on data, which are missing in this case (the only real comparison operation is the bound check), so the linear complexity is give by the F[i-1]+F[i-2]
operation.
来源:https://stackoverflow.com/questions/28927851/time-complexity-of-fibonacci-series