Data Structures & AlgorithmsModerateCognizant · Capgemini pattern
How many times is the base case reached when computing C(5, 2) with the plain recursion C(n, k) = C(n−1, k−1) + C(n−1, k)?
How many times is the base case reached when computing C(5, 2) with the plain recursion C(n, k) = C(n−1, k−1) + C(n−1, k)?
base = 0
def C(n, k):
global base
if k == 0 or k == n:
base += 1; return 1
return C(n - 1, k - 1) + C(n - 1, k)
print(C(5, 2), base)- A. 10 10
- B. 10 5
- C. 10 20
- D. 6 10
Correct answer: A. 10 10
Every leaf of the recursion returns 1 and the answer is the sum of the leaves, so the number of base-case calls equals C(5, 2) = 10 itself – exponential growth for large n. Memoising on (n, k) or using Pascal's triangle makes it O(n·k).
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- What is printed? (Tower of Hanoi: number of moves and the 5th move) python moves = [] def hanoi(n, a, b, c): if n == 0: return hanoi(n…
- What is printed? (recursion output order) python out = [] def f(n): if n == 0: return out.append(n) f(n - 1) out.append(n) f(3) print(out)
- Solve the recurrences numerically: how many 'work units' does each do for n = 64? python from functools import lrucache @lrucache(None)…
- 0/1 knapsack, capacity 50: items (weight, value) = (10, 60), (20, 100), (30, 120). What do greedy-by-ratio and DP give? python items =…
- Activity selection: activities (start, finish). How many can one person attend, and which? python acts = [(1, 4), (3, 5), (0, 6), (5, 7)…
- Huffman coding: frequencies a:5, b:9, c:12, d:13, e:16, f:45. What is the total number of bits to encode the text? python import heapq f =…