![](/img/trans.png)
[英]Heap's Algorithm - Non Recursive Method in Python to generate permutations
[英]Implementing Heap's Algorithm for Permutations in Python
我正在嘗試在 python 中實現 Heap 的算法,但是在重復某些解決方案時遇到了麻煩。 我對錯誤所在的位置感到困惑。 這是實現:
import copy
def _permute(l, n):
if n == 1:
print(l)
else:
for i in range(n - 1):
# note: must copy here, or all answers will be same
new_arr = copy.copy(l)
_permute(new_arr, n - 1)
if n % 2 == 0:
l[i], l[n - 1] = l[n - 1], l[i]
else:
l[0], l[n - 1] = l[n - 1], l[0]
_permute(l, n - 1)
對於輸入[0, 1, 2]
和3
,我得到:
[0, 1, 2]
[1, 0, 2]
[2, 1, 0]
[1, 2, 0]
[0, 1, 2] ** repeats from first answer **
[1, 0, 2] ** repeats from second answer **
最后 2 個結果,從第一個和第二個重復,丟失:
[0, 2, 1]
[2, 0, 1]
我搜索了多個地方並嘗試了該算法的不同實現,但無論我嘗試多少次,我似乎都無法讓它工作。 我錯過了什么?
您將遞歸調用放在錯誤的位置,這應該可以解決問題(並且您不應該使用副本):
def _permute(l, n):
if n == 1:
print(l)
else:
_permute(l, n - 1)
for i in range(n - 1):
if n % 2 == 0:
l[i], l[n - 1] = l[n - 1], l[i]
else:
l[0], l[n - 1] = l[n - 1], l[0]
_permute(l, n - 1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.