我想在寻找独特排列的问题中使用回溯。我写了这个:使用回溯的独特排列
def f(A, start, end):
if start == end - 1:
print(A)
else:
for idx in range(start, end):
if idx != start and A[idx] == A[start]:
continue
A[idx], A[start] = A[start], A[idx]
f(A, start + 1, end)
此示例适用
A = [2, 3, 2]
f(A, 0, len(A))
[2, 3, 2]
[2, 2, 3]
[3, 2, 2]
这一个不工作
A = [2, 2, 1, 1]
f(A, 0, len(A))
[2, 2, 1, 1]
[2, 1, 2, 1]
[2, 1, 1, 2]
[2, 2, 1, 1] #unwanted duplicate!
[1, 2, 2, 1]
[1, 2, 1, 2]
[1, 1, 2, 2]
[1, 2, 2, 1]
[1, 2, 1, 2]
[2, 2, 1, 1]
[2, 1, 2, 1]
[2, 1, 1, 2]
[2, 2, 1, 1]
为什么我仍然有结果的重复?
好吧,你有'A = [2,2,1,1]','在F',你也会调用'f([2,1,2,1],1,len(A)',并且这两种情况都可以输出'[2,2,1,1]'(第一个没有排列,第二个排列在元素之间)的索引1和2) – Nuageux