Basic Tools of the Trade 27
TABLE 2.1: Compositions of n with 1s and 2s
n # of compositions compositions
1 1 1
2
2 11, 2
3
3 111, 12, 21
4
5 1111, 112, 121, 211, 22
5
8 11111, 1112, 1121, 1211, 122, 2111, 212, 221
The resulting sequence for the number of compositions looks very much like
the Fibonacci sequence, except it does not start correctly. We also have to
check whether this Fibonacci pattern continues beyond the first few values.
Let’s think about a systematic way to create the compositions of n in {1, 2}
recursively. Each such composition of n (for n ≥ 2) either starts with a 1
or a 2. We can create those starting with a 1 by appending a composition of
n −1,andthosestartingwitha2 by appending a composition of n − 2.Itis
customary to define the number of compositions of 0 to be 1(for the empty
composition). If we denote the number of compositions of n in {1, 2} by C
n
,
then we obtain the following recursion:
C
n
= C
n−1
+ C
n−2
,C
0
= C
1
=1,
which results in the shifted Fibonacci sequence.
Example 2.10 (Words avoiding given substrings) Let’s determine a
n
,the
number of words of length n on the alphabet {1, 2, 3} which do not start with
3 and do not contain the substrings 13, 22, 31,and32. If the word starts with
a 1, we can append any of the a
n−1
such words of length n − 1.Iftheword
starts with a 2, then the second letter has to be a 1 or a 3, that is, the word
starts with 21 or with 23. In the first case, there are no restrictions on how
the word can continue, so we can append any word of length n −2 without the
forbidden substrings, for a total of a
n−2
such words. If the word starts with
23, then the only possible words are of the form 233 ···3, and there is exactly
one. The initial conditions are a
0
=1and a
1
=2. Overall,
a
n
= a
n−1
+ a
n−2
+1,a
0
=1,a
1
=2.
In these two examples, the recurrence relation was very easy to derive,
whereas an explicit formula is hard to obtain directly. Very often, a recursive
relation can be obtained naturally, as it expresses how a sequence evolves
from one step to the next. Notice how we divided the objects to be counted
into classes or categories, each of which is counted separately. In the example
above, we focused on the first part of the composition or word. In the case
of the compositions, we could have just as easily focused on the last part, as
each composition either ends in a 1 or a 2. Focusing on the first and last
© 2010 by Taylor and Francis Group, LLC