Recursion · Pascal's triangle · Branching tree

Binomial Coefficient Visualizer

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

Base case Choosing nothing, or choosing every remaining item, can be done in one way. Return 1.
Recursive case 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

Interactive recursion tree
Step 0/0 Answer —

The whole tree is drawn when the page opens. Next and Play start again from the first call.

def C(n, k):
if k == 0 or k == n:
return 1
return C(n - 1, k - 1) + C(n - 1, k)

Complexity

PieceCostWhy
TimeO(2^n)Each call makes two smaller calls, and the same pair repeats.
StackO(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)