Combinatorics

This week, we're focusing on combinatorics, or counting things! This shows up in competitions all the time, and judges (especially Chip), love writing combinatorics problems. Be careful, integer overflows abound here! You'll need to watch all of your intermediate calculations to make sure they don't get too big.

Delving Deeper

Here is a counting problem that's very elegant if written recursively. However, do note that the recursive function that models this problem uses a second variable aside from k.

It's also worth noting that this problem is not only recursive, but exhibits Optimal Substructure. That means that it's solution can be computed efficiently from smaller versions of the problem (it's recursive nature). Moreover, it has Overlapping Subproblems, meaning C(k, n) might end up calculating smaller subproblems multiple times. However, Dynamic Programming provides relief to this problem (see the first paragraph, and the "In Computer Programming" section.

Look at this visualization on recursion (in particular the Fibonacci numbers for n=5 or 6). Note that F(2) is calculated multiple times in the recursion tree. That's the essense of Dynamic programming: Put previously calculated values in a table so you don't recopy them. The Python dict or Java HashMap are excellent choices for this, but you may need a tuple Python or custom object as your key in order to map multiple items (sometimes people use multi-dimensional arrays for that reason).