1. 程式人生 > 其它 >16位彙編 04

16位彙編 04

對於一般的全排列問題,使用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