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
这个问题是否存在一种通用的模式/解决方案?
这个问题被称为 划分问题,详见维基百科引用链接中的说明:
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
。
n
计算为n
的一个分区。 - unutbuP(n)
(或P(1,n))(只输出值),它应该从1中减去。我已经编辑了我的答案,谢谢。 - Saeed Amiri