What is Binomial Coefficient
Return C(n, k), the number of ways to choose k items from n. C(n, 0) and C(n, n) are 1.
Example. C(4, 2) = 6. Each call splits into "take one item" and "skip it".
Input: 4 2 Output: 6
Constraints. 0 ≤ k ≤ n ≤ 18. The same subproblem appears on more than one branch. These limits keep a direct recursion fast enough. This picture caps n at 4.
Approach
C(n, k) = C(n - 1, k - 1) + C(n - 1, k). The left edge takes an item. The right edge skips it.Identical pairs such as C(2, 1) are computed again on separate branches. That repeated work is the reason this recurrence later becomes a dynamic-programming table.
Recursion tree
The whole tree is drawn when the page opens. Next and Play start again from the first call.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(2^n) | Each call makes two smaller calls, and the same pair repeats. |
| Stack | O(n) | The deepest chain reduces n down to a base case. |
Implementation
def C(n, k):
if k == 0 or k == n:
return 1
return C(n - 1, k - 1) + C(n - 1, k)