According to this post, we know how to determine the complexity for recursive function.
However, for the codes below,
const int N = 100, W = 100000;
int p[N][W + 1]; // the values of element in the array p are 0, 1, 2.
int output[N];
void find_path(int n, int w, int k) {
if (n < 0) {
for (int i=0; i<k; ++i) cout << output[i];
return;
}
if (p[n][w] == 0) {
find_path(n-1, w, k); // the 1st branch
}
else if (p[n][w] == 1) {
output[k] = n;
find_path(n-1, w-weight[n], k+1); // the 2nd branch
}
else if (p[n][w] == 2) {
output[k] = n; // the 3rd branch
find_path(n-1, w-weight[n], k+1);
find_path(n-1, w, k);
}
}
Here is my analysis:
T(n) = T(n-1) + a // the 1st branch
T(n-1) + b // the 2nd branch
2*T(n-1) + c // the 3rd branch
At the first glance, the 3rd branch takes more time than the other two branches, Could I just ignore the 1st and 2nd branch?, so the complexity could be T(n)=2*T(n-1)
, and the result is O(2^n)
, Am I right?
Moreover, what if there is one more find_path
invocation in the 2nd branch
else if (p[n][w] == 1) {
output[k] = n;
find_path(n-1, w-weight[n], k+1); // the 2nd branch
find_path(n-1, w, k+1);
}
How to compute the time complexity in this case?