1

I try to determine the runtime complexity of the following code. I came up with T(n) = n * T(n-1) + n where T(0) = 1 but not sure if it's correct and how to solve it.

private void myFunction(int[] nums, int startIndex, int target) {
    if (target == 0) {
        // do something
    }
    if (target <= 0 || start > nums.length) {
        return;
    }

    for (int i = startIndex; i < nums.length; i++) {
        myFunction(nums, i+1, target-nums[i]);
    }
}

myFunction(nums, 0, target);
Chathura Buddhika
  • 2,067
  • 1
  • 21
  • 35
S.H.
  • 83
  • 6

1 Answers1

0

I guess the recurrence relation for the function is T(n) = n * T(n-1) + O(1), where T(0) = 1

Reduction:

T(n) 
= n * T(n-1) + O(1)
= n * (n-1) * T(n-2) + 1 + 1
= n * (n-1) * (n-2) * T(n-3) + 1 + 1 + 1
...
= n * (n-1) * (n-2) * (n-3) ... T(0) + n * 1 (n times)
= n! + n

Hence, the overall complexity for the function is O(n!) which is greater O(2n). More details.

Hope it helps!

arunk2
  • 2,246
  • 3
  • 23
  • 35