IntermediateMath for DSADynamic Programming

Choosing k of n: nCr and Pascal's triangle

C(n, k) = n! / (k!(n−k)!) counts ways to choose. Unique Paths on an m×n grid is C(m+n−2, m−1): no DP needed.

The idea

C(n, k) is the number of ways to pick k items out of n when order doesn't matter. C(5, 2) = 10: the 10 pairs from 5 people.

Pascal's rule, C(n, k) = C(n−1, k−1) + C(n−1, k), says “either item n is picked or it isn't”, which is exactly a DP . Many grid and choice problems are secretly this formula.

Worked example

Unique Paths in a 3 × 7 grid (only right or down)

  1. Every path is 2 downs and 6 rights: 8 moves in total.
  2. A path is decided by which 2 of the 8 moves are downs.
  3. C(8, 2) = 8 × 7 / 2 = 28 paths.

Pseudocode

The steps in plain words. ← means “set to”; indentation shows what's inside what.

C(n, k):
k ← min(k, n − k)
result ← 1
for i from 1 to k:
result ← result × (n − k + i) // i(whole at every step)
return result
grid paths (m × n) = C(m + n − 2, m − 1)

See it run

The worked example, step by step, beside the Python. The highlighted line is the one running.

Step-by-step

3 × 7 grid

moves = 8downs = 2

Solution · Pythonline 9

def n_choose_k(n, k):
k = min(k, n - k)
result = 1
for i in range(1, k + 1):
result = result * (n - k + i) // i # stays an integer at every step
return result
def unique_paths(m, n):
return n_choose_k(m + n - 2, m - 1)

Step 1 of 5· line 9

Every path is 2 downs and 6 rights: 8 moves. Choosing which 2 of the 8 moves are downs fixes the path, so the answer is C(8, 2).

O(k) multiplications.

How to spot it

  • “number of ways to choose / arrange”, lattice paths on a grid, rows of Pascal's triangle.

Common mistakes

  • Computing n! first: huge numbers (and outside Python).
  • Mixing up (order doesn't matter) and (it does).

Practise the ideas first

Where it comes up

Go further