全排列问题

对于一般的全排列问题,使用DFS递归方法即可:

n=int(input())
l=[]
for i in range(1,n+1):
    l.append(i)
def swmp(l,i,j):
    l[i],l[j]=l[j],l[i]
def fun(l,k):
    if k==n-1:
        print(l)
        return
    for i in range(k,n):
        swmp(l,k,i)
        fun(l,k+1)
        swmp(l,k,i)
fun(l,0)
View Code

但是可以看出,此全排列输出并不是按字典序排列的:

[1, 2, 3, 4]
[1, 2, 4, 3]
[1, 3, 2, 4]
[1, 3, 4, 2]
[1, 4, 3, 2]
[1, 4, 2, 3]
[2, 1, 3, 4]
[2, 1, 4, 3]
[2, 3, 1, 4]
[2, 3, 4, 1]
[2, 4, 3, 1]
[2, 4, 1, 3]
[3, 2, 1, 4]
[3, 2, 4, 1]
[3, 1, 2, 4]
[3, 1, 4, 2]
[3, 4, 1, 2]
[3, 4, 2, 1]
[4, 2, 3, 1]
[4, 2, 1, 3]
[4, 3, 2, 1]
[4, 3, 1, 2]
[4, 1, 3, 2]
[4, 1, 2, 3
output

如果要按照字典序排列进行输出,那么为了保持大小顺序,不只是要调换两个数的值,而是循环移动,代码如下:

n=int(input())
l=[]
for i in range(1,n+1):
    l.append(i)
def swmpgo(l,i,j):
    for x in range(j,i,-1):
        l[x-1],l[x]=l[x],l[x-1]
def swmpback(l,i,j):
    for x in range(i,j):
        l[x],l[x+1]=l[x+1],l[x]
def fun(l,k):
    if k==n-1:
        print(l)
        return
    for i in range(k,n):
        swmpgo(l,k,i)
        fun(l,k+1)
        swmpback(l,k,i)
fun(l,0)
View Code

此时,全排列的输出是按照字典顺序来的:

[1, 2, 3, 4]
[1, 2, 4, 3]
[1, 3, 2, 4]
[1, 3, 4, 2]
[1, 4, 2, 3]
[1, 4, 3, 2]
[2, 1, 3, 4]
[2, 1, 4, 3]
[2, 3, 1, 4]
[2, 3, 4, 1]
[2, 4, 1, 3]
[2, 4, 3, 1]
[3, 1, 2, 4]
[3, 1, 4, 2]
[3, 2, 1, 4]
[3, 2, 4, 1]
[3, 4, 1, 2]
[3, 4, 2, 1]
[4, 1, 2, 3]
[4, 1, 3, 2]
[4, 2, 1, 3]
[4, 2, 3, 1]
[4, 3, 1, 2]
[4, 3, 2, 1]
output

 另一个对顺序数字全排的简单方法:

n=int(input())
bol=[0]*n
l=[0]*n
def dfs(dep):
    if dep==n:
        print(l)
        return
    for i in range(n):
        if bol[i]==0:
            l[dep]=i+1
            bol[i]=1
            dfs(dep+1)
            bol[i]=0
dfs(0)
View Code

 

posted @ 2022-03-07 12:09  不正从心szd  阅读(40)  评论(0编辑  收藏  举报