简体   繁体   中英

Algorithm to count the number of partitionings?

Recently, I ancountered the problem to evenly disperse different width-sized, small containers into huge width-sized containers horizontally. There are millions of huge containers with billions of small containers. I need to come up with an algorithm. I simplified the problem into the below question:

Let's use Process(Number,Parts) as an example:

Number 4 can be split into 2 parts in 3 ways (not including 0). Process(4,2)=3 :

1 + 3
3 + 1
2 + 2

Likewise, number 4 can be split into 3 parts in 2 ways Process(4,3)=2 :

1 + 1 + 2
2 + 1 + 1
1 + 2 + 1

And obviously Process(4,4)=1

(not including Process(4,1)=1 , because it is 4+0 , where 0 shouldn't be taken into consideration)

I wonder whether there is any way to calculate

SuperProcess(4)=Process(4,2)+Process(4,3)+Process(4,4)=7

with less time complexity? Or with another word, faster!!

Especially when the request is to calculate: SuperProcess(1209)

Is there some mathematical method rather than a crude loop to perform this calculation?

SuperProcess(n) is known as the number of compositions of an integer rather than the number of partitions in which sums containing the same addends are considered identical independent of ordering.

There are exactly 2**(n-1)-1 compositions for a positive integer n excluding the sum with only one addend.

Therefore the best algorithm to calculate SuperProcess(n) is simply to evaluate the expression 2**(n-1)-1 , which can be done in Theta(n) time.

If you want to enumerate all combinations, this can be done with a recursive function taking every value 1...n for the integer m in the current position in the sum and then recursively calling itself with nm for the next position, stopping on 0 argument.

The enumeration algorithm will take Theta(n 2**n) time and this is optimal, because it is the time required to save/print all the combinations explicitly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM