获得总和为n的方法数,且所有小于n的正整数均参与运算。

7
对于给定的数字n,例如2,使用小于2的数字有多少种方法可以得到总和为2。
1+1 = 2  
so, for 2 - just 1 way.

n = 3   
1+1+1=3  
1+2=3  
so,for 3 - it is 2 ways  
n = 4   
1+1+1+1=4  
1+1+2=4  
1+3=4  
2+2=4  

so, for 4 - it is 4 ways  

这个问题是否存在一种通用的模式/解决方案?
1个回答

12

这个问题被称为 划分问题,详见维基百科引用链接中的说明:

One way of getting a handle on the partition function involves an intermediate function p(k, n), which represents the number of partitions of n using only natural numbers at least as large as k. For any given value of k, partitions counted by p(k, n) fit into exactly one of the following categories:

smallest addend is k
smallest addend is strictly greater than k.

The number of partitions meeting the first condition is p(k, n − k). To see this, imagine a list of all the partitions of the number n − k into numbers of size at least k, then imagine appending "+ k" to each partition in the list. Now what is it a list of? As a side note, one can use this to define a sort of recursion relation for the partition function in term of the intermediate function, namely

1+ sum{k=1 to floor (1/2)n} p(k,n-k) = p(n),

The number of partitions meeting the second condition is p(k + 1, n) since a partition into parts of at least k that contains no parts of exactly k must have all parts at least k + 1.

Since the two conditions are mutually exclusive, the number of partitions meeting either condition is p(k + 1, n) + p(k, n − k). The recursively defined function is thus:

p(k, n) = 0 if k > n

p(k, n) = 1 if k = n

p(k, n) = p(k+1, n) + p(k, n − k) otherwise.

实际上,您可以通过记忆化计算所有值,以防止额外的递归调用。

编辑:正如unutbu在他的评论中提到的那样,在计算结束时,您应该减去1以输出结果。也就是说,在最后一步之前,应按照维基百科的建议计算所有P值,但在输出结果之前,您应将其减去1


为了将其与 OP 的计数方式联系起来,我们必须从 p(1,n) 中减去 1,因为 OP 没有将 n 计算为 n 的一个分区。 - unutbu
@unutbu 是的,但最终结果应该从1中减去,实际上所有的P(i,j)都将按照上面(在维基百科中)写的方式计算,但对于P(n)(或P(1,n))(只输出值),它应该从1中减去。我已经编辑了我的答案,谢谢。 - Saeed Amiri

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接