Finally, let's gather all the stones we've thrown. I mentioned calculating the whole n-th row in Pascal's triangle in T=O(n), M=O(1). There was also leetcode 62, a problem about the number of paths a robot can take through a rectangular grid. I explained how to skew Pascal's triangle into that rectangular grid and showed what the recurrence relation between its elements looks like.

There are four ways to define the numbers that live in Pascal's triangle. It's a beautiful crossroads, and I hope that one day I'll write about it.

In the previous posts, we discussed two out of four: CnkC_n^k is the number of ways to place k indistinguishable objects in a row of n cells, with at most one object per cell; it is also the kth element in the nth row of Pascal's triangle. To solve the problem, we'll use the third definition:

Cnk=n!k!(n−k)!C_n^k = \frac {n!} {k!(n-k)!}

Let's take one step along the nth row. Unexpected question: what is the ratio between two neighbors, CnkC_n^k and Cnk+1C_n^{k+1} ? The math is quite simple:

Cnk+1Cnk=n!(k+1)!(n−k−1)!n!k!(n−k)!=n!(k+1)!(n−k−1)!⋅k!(n−k)!n!=k!(k+1)!⋅(n−k)!(n−k−1)!=n−kk+1\frac{C_n^{k+1}}{C_n^k} = \frac{\frac{n!}{(k+1)!(n-k-1)!}}{\frac{n!}{k!(n-k)!}} = \frac{n!}{(k+1)!(n-k-1)!} \cdot \frac{k!(n-k)!}{n!} = \frac{k!}{(k+1)!} \cdot \frac{(n-k)!}{(n-k-1)!} = \frac{n-k}{k+1}

In this math you strike out k!k! in numerator with factorial sign in denominator. Funny.

Taking all this into account, the program from that post becomes trivial. Ta-da!!!