我目前正在用 Python 实现 Heaps 的算法,但我目前的解决方案是两次返回一些排列。
def generate(startingIndex, alist):
if startingIndex == 1:
print(alist)
else:
for i in range(0, len(alist)):
generate(startingIndex - 1, alist)
if i % 2 == 1:
alist[0], alist[startingIndex - 1] = alist[startingIndex - 1], alist[0]
else:
alist[i], alist[startingIndex - 1] = alist[startingIndex - 1], alist[i]
generate(3, ["a", "b", "c"])
此代码产生以下结果:
['a', 'b', 'c'] #this will be repeated
['b', 'a', 'c']
['a', 'b', 'c'] #here
['b', 'c', 'a'] #this will be repeated
['c', 'b', 'a']
['b', 'c', 'a'] #here
['c', 'a', 'b'] #this will be repeated
['a', 'c', 'b']
['c', 'a', 'b'] #here
由于我不想要重复的结果,
我究竟做错了什么?