Data Structures & AlgorithmsHardProduct-company placement

How many calls of g (including the first) are made when g(8) is evaluated, and what value is returned?

How many calls of g (including the first) are made when g(8) is evaluated, and what value is returned?
int g(int n) {
    if (n <= 2) return n;
    return g(n - 1) + g(n - 2) + g(n - 3);
}
  1. A. 85 calls, returns 68
  2. B. 9 calls, returns 68
  3. C. 85 calls, returns 69
  4. D. 79 calls, returns 68

Correct answer: A. 85 calls, returns 68

calls(n) = 1 + calls(n−1) + calls(n−2) + calls(n−3) with calls = 1 for n ≤ 2 (and n = 0, 1, 2 return 0, 1, 2), giving 85 calls and value 68. With memoisation only 9 distinct calls would compute.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic