The Question
I am having trouble finding the time complexity of the following algorithm:
void f2(int n) {
int i;
if (n == 1) {
return;
}
for (i = 0; i < n; i++) {
f2(n - 1);
}
}
My Problem
The solution I came to is O(2^n) but the right answer is stated as O(n!) and I do not understand how that is possible and would be really grateful if somebody could explain it to me.
for (i = 0; i < n; i++) {
f2(n - 1);
}
so outer loop runs n times, and recursively calls (n times) a inner loop which runs n-1 times, until you reach 1.
So it runs n!
times all right.
Consider below function
void fact(int n) {
int i;
if (n == 1) {
return;
}
for(int i=0; i<n; i++) {
fact(n-1);
}
}
Assume n=2
;
the function becomes
void fact(int n) {
fact(1);
fact(1);
}
Seems like time complexity is exponential.
Now Assume n=4
void fact(int n) {
fact(3);
// -- this leads to fact(2) fact(2) fact(2)
// -- which leads to fact(1) fact(1) fact(1) fact(1) fact(1) fact1)
fact(3);
fact(3);
fact(3);
}
ultimately it ends up with O(n!)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.