Memoization

Efficient Implementation of the Non-Adjacent Selection Formula

In the previous post, we derived the closed form for the non-adjacent selection problem:

$$ F_{n, m} = {n - m + 1 \choose m} $$

Now we discuss how to implement this efficiently in Python—from a simple factorial-based solution to library implementations. For the common case of computing the answer modulo a large prime (e.g. in competitive programming), see the next post.

Fast Solutions Based on Binomials

We can reflect the closed form in very trivial Python code:

Cracking Multivariate Recursive Equations Using Generating Functions

In this post, we return back to the combinatorial problem discussed in Introduction to Dynamic Programming and Memoization post. We will show that generating functions may work great not only for single variable case (see The Art of Generating Functions), but also could be very useful for hacking two-variable relations (and of course, in general for multivariate case too).

For making the post self-contained, we repeat the problem definition here.

The Problem

Compute the number of ways to choose $m$ elements from $n$ elements such that selected elements in one combination are not adjacent.