我想要生成n列表的所有排列,n列表的最大值爲n-1,例如,對於n = 3,所有可能的清單如下生成所有具有最大值爲n-1的n列表,並且沒有遞歸python
[0,0,0]
[0,0,1]
[0,0,2]
[0,1,0]
[0,1,1]
[0,1,2]
[0,2,0]
...
[2,2,2]
我意識到這非常迅速地增長非常大(有n^n個排列)。我現在有一個使用遞歸
def generatePermutations(allPerms, curPerm, curIndex, n):
#allPerms is a reference to the full set of permutations
#curIndex is the index which is currently being changed
if (curIndex == n - 1):
for i in range(n):
curPerm[curIndex] = i
allPerms.append(list(curPerm))
else:
for i in range(n):
curPerm[curIndex] = i
#recursively generate all permutations past our curIndex
generatePermutations(allPerms, curPerm, curIndex + 1, n)
allPermutations = []
currentPermutation = []
n = 4
for i in range(n):
currentPermutation.append(0)
generatePermutations(allPermutations, currentPermutation, 0, n)
在試圖找到一個非遞歸的解決方案,我碰了壁,我想下面的工作代碼也必須是嵌套的循環n號,我無法弄清楚如何爲任意n做。我唯一的想法是做一些花式的添加包含循環的列表以便以某種方式運行,或者甚至更荒謬,通過編程生成代碼並將它傳遞給eval調用。我的直覺告訴我這些比必要的更復雜。任何人都可以想出解決方案嗎?謝謝!
'和itertools.permutations()'會做這給你一個電話。但是你可能不想聽到這個...... –
然而,你並沒有產生排列組合。你正在生產一種產品。 –