3 回答

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超10個(gè)贊
它稱為分區(qū)。[另請(qǐng)參閱Wikipedia:分區(qū)(數(shù)論)。]
分區(qū)的數(shù)量p(n)呈指數(shù)增長(zhǎng),因此生成所有分區(qū)的所有操作都必須花費(fèi)指數(shù)時(shí)間。
也就是說,您可以做得比代碼更好。請(qǐng)參見David Eppstein在Python Algorithms and Data Structures中的此版本或其更新版本。

TA貢獻(xiàn)1807條經(jīng)驗(yàn) 獲得超9個(gè)贊
這是我在Python中的解決方案(指數(shù)時(shí)間):
q = { 1: [[1]] }
def decompose(n):
try:
return q[n]
except:
pass
result = [[n]]
for i in range(1, n):
a = n-i
R = decompose(i)
for r in R:
if r[0] <= a:
result.append([a] + r)
q[n] = result
return result
>>> decompose(5)
[[5], [4, 1], [3, 2], [3, 1, 1], [2, 2, 1], [2, 1, 1, 1], [1, 1, 1, 1, 1]]
添加回答
舉報(bào)