Wednesday, May 28, 2008

Problem: Number Partitioning

Had a go to derive a formula for the number of partitions of a number. Initially, tried to compare it with the 'pirates and gold bars' problem and see if I could derive some formula based on similar reasoning. After this failed attempt, decided to come up with a recursive formula.

Suppose you order the partitions by increasing size, and within a partition order the elements in weakly increasing order. For example, you write the partitions of 4 as:
4
1 3
2 2
1 1 2
1 1 1 1

Now, consider a way of generating all the partitions of a given size k. Suppose these partitions are to be arranged lexicographically. Then, the first partition consists of (k-1) 1s followed by the number n-(k-1). For example, the first 4-sized partition of 8 would be:
1 1 1 5

The next partition is generated by taking 1 away from the rightmost element (rightmost_elem) and adding it to the previous element. This process should be continued upto the point where the elements within the partition cannot be arranged in weakly increasing order. So, we have:
1 1 1 5
1 1 2 4
1 1 3 3
(cant go for 1 1 4 2)

For each of the partitions generated above, partitions for the (k-1) leftmost elements can be generated keeping the rightmost element constant. Hence, this can be viewed as a recursive process of generating sub-partitions for the number (n - rightmost_elem), each of size (k-1). Also, while generating these sub-partitions, the maximum value of any element should not exceed the value of the rightmost_elem.

This idea of recursive sub-partitions is captured by the following recurrence equation:
And the following equation generates all partitions of a number:
We also need to take care of the end conditions properly. If k ==1, only 1 partition is possible and when n==k, only 1 partition is possible i.e. T(n,1,max) = 1 and T(n,n,max) = 1.

No comments: