Generating functions can be used for counting.
Consider the problem of finding the number of trees with internal nodes.
Let T be the set of all binary trees. Let |t| be the number of internal nodes in tree t. Let TN be the number of trees with |t|=N.
Then T(z)=∑t∈Tz|t|=∑N≥0TNzN.
Note the two different ways of writing the sum.
General Approach
- Let P be the set of all given objects.
- Let p∈P be an element of that object.
- Let PN be the number of elements with |p|=N.
- Let cost(p) be the “cost” of p.
- Let PNk be the number of p with |p|=N and cost(p)=k.
- Define the cumulative cost to be CN=∑k≥0kPNk.
- Define the cumulative function to be C(z)=∑N≥0CNzN=∑p∈Pcost(p)z|p|.
Now the expected cost of size N is:
CNPN
Or, using generating functions:
[zN]C(z)[zN]P(z)
Notes
Note that this equality:
C(z)=∑N≥0CNzN=∑p∈Pcost(p)z|p|.
allows you to generate identities by computing something in two different ways.