Illustration for “Calculating a row of Pascal's triangle in linear time: Part 2” (1 of 3)

It's the famous Pascal's triangle. Ones on the roof. Each element below is equal to the sum of its two upstairs neighbors. My first attempt to write a program that calculated Pascal's triangle, thirty years ago, failed because I actually tried to reproduce this equilateral picture from books.

Illustration for “Calculating a row of Pascal's triangle in linear time: Part 2” (2 of 3)

When I draw it like this, it becomes way more programming-friendly. We pay for it with left-right symmetry, but in return we get a clear and uniform recurrence relation:

Cnk=Cn−1k+Cn−1k−1C_n^k = C_{n-1}^k + C_{n-1}^{k-1}

The neighbors now live directly upstairs and upstairs to the left.

The next thing with which I'm not quite comfortable even now is skew transform:f(x,y)=Cx+yxf(x, y) = C_{x + y}^x. It's because we are talking about the robot who wants to make x steps to the right (x ones) and y steps down (y zeros). There are Cx+yxC_{x + y}^x ways to create the string which consists of x ones and y zeros. Or Cx+yyC_{x + y}^y - because of the symmetry. This way you can see exactly the table from the previous post.

Illustration for “Calculating a row of Pascal's triangle in linear time: Part 2” (3 of 3)

So far, we've seen two faces of binomial coefficients: recurrence and combinatorics. Now we can use them to count paths for the robot. Be careful. In the problem statement mm and nn are height and width of the rectangular grid. The numbers of steps in each direction is one smaller: x=m−1x = m - 1 to the right and y=n−1y=n-1 down. One last step remains: calculate Cx+yyC_{x + y}^y efficiently. Let's do it next time.