【发布时间】:2020-05-25 15:55:33
【问题描述】:
我试图在寻找唯一排列的问题中使用回溯。我写了这个:
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)
标签: python permutation backtracking