Search code examples
javarecursiondynamic-programmingpartitioninginteger-partition

Integer partitioning in Java


I'm trying to implement a program that returns the number of existing partitions of an integer n as part of an assignment. I wrote the code below, but it returns the wrong number (Partitions n returns the result of Partitions n-1). I don't get why this happens. I've tried many things and still don't know how to fix it, can anyone please help me?

[edited code out to avoid plagiarism from my colleagues :p]

m stands for the biggest number allowed in a partition, so partition(4,4) would be 5 = 4, 3+1, 2+2, 2+1+1, 1+1+1+1, but partition (4,1) would be 1 = 1+1+1+1. Execution: java Partitions n


Solution

  • Suppose you're calling partitions(4,4,memo). As you said, the answer should be 5 because there are 5 ways to partition the integer:

    4
    3 + 1           <== counted by partition(1,3,memo)
    2 + 2           <== counted by partition(2,2,memo)
    2 + 1 + 1       <== counted by partition(2,2,memo)
    1 + 1 + 1 + 1   <== counted by partition(3,1,memo)
    

    So it looks like your algorithm tries to count the partitions in the way shown above... but is there one partition you're forgetting to count?