Find Binomial coefficient (Tabulation)

A binomial coefficient, n choose k formula, is also known as combinations formula, and is defined as

( n 0 ) = ( n n ) = 1 and ( n k ) = n (n-1) (n-k+1) k (k-1) (1) = n k ( n-1 k-1 ) for n k 0

Hint

Building upon understanding of Binomial coefficient (Memoization). Tabulation essentially reconstructs the cache.

Start with the foundation – the base cases, which are the simplest solutions. Then, layer by layer, use the results of the previous layers to calculate the solutions for the next level. This way, we systematically build up the entire solution, avoiding redundant calculations and ensuring efficiency. It is like building a pyramid.

The underlying calculation logic remains fundamentally identical to the original recursive approach, albeit executed in reverse order.

# Python implementation
def binomial(n, k):
  cache = [[0 for _ in range(k + 1)] for _ in range(n + 1)]

  for i in range(n+1):
    cache[i][0] = 1

  for i in range(k+1):
    cache[0][i] = 0

  for i in range(1, n + 1):
    for j in range(1, k + 1):
      cache[i][j] = (float(i) / j) * cache[i - 1][j - 1]

  return cache[n][k]

n = 10
k = 5

print(binomial(n, k))
// Javascript implementation
function binomial(n, k) {
  const cache = Array(n + 1);

  for (let i = 0; i < cache.length; i++) {
    cache[i] = Array(k + 1).fill(0);
  }

  for (let i = 0; i < n + 1; i++) {
    cache[i][0] = 1;
  }

  for (let i = 0; i < k + 1; i++) {
    cache[0][i] = 0;
  }

  for (let i = 1; i < n + 1; i++) {
    for (let j = 1; j < k + 1; j++) {
      cache[i][j] = (i / j) * cache[i - 1][j - 1];
    }
  }

  return cache[n][k];
}

const n = 10;
const k = 5;

console.log(binomial(n, k));