要点:
1. 不重:同值元素相对位置不变;
2. 不漏:枚举不遗漏;
perm_0参考y总讲解,实际运行速度更快些,并且天然保持字典顺序;
perm_1参考通过交换源数组[]的元素位置来获取全排列,按照字典顺序输出需要重排序;
def perm_0(arr):
res = []
n = len(arr)
undo = [True] * n
path = [0] * n
def dfs(i):
if i >= n - 1:
res.append(list(arr))
return
j = 0
while j < n:
if undo[j]:
undo[j] = False
path[i] = arr[j]
dfs(i + 1)
undo[j] = True
while j + 1 < n and arr[j]== arr[j + 1]: j += 1
j += 1
dfs(0)
return res
def perm_1(arr):
res = []
n = len(arr)
def dfs(i):
if i >= n:
res.append(list(arr))
return
j = i
while j < n:
nojump=True
val = arr[j]
for p in range(i, j):
if arr[p] == val:
nojump = False
break
if nojump:
arr[i], arr[j] = arr[j], arr[i]
dfs(i + 1)
arr[i], arr[j] = arr[j], arr[i]
j += 1
dfs(0)
return sorted(res)
perm = perm_0
perm = perm_1
n = int(input())
arr = sorted(map(int, input().split()))
for cur in perm_1(arr):
print(' '.join([str(i) for i in cur]))