Integer partitioning in Java

这一生的挚爱 提交于 2021-02-20 04:14:48

问题


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


回答1:


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?



来源:https://stackoverflow.com/questions/44359310/integer-partitioning-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!