0

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?

Community
  • 1
  • 1
zangw
  • 33,777
  • 15
  • 127
  • 153

1 Answers1

1

Yes, you should take their maximum (for the worst case), which corresponds to the third branch. Because of that, you can ignore the 1st and 2nd branches. Then, the recurrence is T(n)<=2T(n-1)+O(1), so that T(n)=O(2^n).

For the same reason, you can add the new call to the 2nd branch "for free".

anumi
  • 3,744
  • 1
  • 20
  • 22