Topics

The core idea is based on pascal’s triangle, where each entry is the sum of the two entries directly above it.

The algorithm constructs a table C where C[i][j] stores the value of . The base cases are . The binomial coefficient recursive relation is:

This relation allows us to build the table row by row, avoiding redundant calculations. The final result, , is then found at C[n][r].

def nCr(n, r):
    C = [[0]*(r+1) for _ in range(n+1)]
    for i in range(n+1):
        for j in range(min(i, r)+1):
            if j == 0 or j == i:
                C[i][j] = 1
            else:
                C[i][j] = C[i-1][j-1] + C[i-1][j]
    return C[n][r]

T.C:
S.C: