python排列组合算法

其实和八皇后的算法差不多,八皇后不检查斜线的结果就是全排列,此外八皇后中检查皇后位置麻烦,这里只要把列表转成词典,检查一下长度就行了(有重复元素,比如到第二层,应该是1,2,如果是1,1,那么词典长度就只有1了,需要排除)

组合就是每次取得必须是大于之前的,排列就是每次都从0开始选:

def combination(n,c,com=1,limit=0,per=[]):
    for pos in range(limit,n):
        t = per + [pos]
        if len(set(t)) == len(t):
            if len(t) == c:
                    yield [pos,]
            else:
                    for result in combination(n,c,com,com*pos, per + [pos,]):
                            yield [pos,] + result
print("排列:")
for res in combination(5,3,0):
    print(res)

print("组合:")
for res in combination(5,3):
    print(res)

结果:

排列:
[0, 1, 2]
[0, 1, 3]
[0, 1, 4]
[0, 2, 1]
[0, 2, 3]
[0, 2, 4]
[0, 3, 1]
[0, 3, 2]
[0, 3, 4]
[0, 4, 1]
[0, 4, 2]
[0, 4, 3]
[1, 0, 2]
[1, 0, 3]
[1, 0, 4]
[1, 2, 0]
[1, 2, 3]
[1, 2, 4]
[1, 3, 0]
[1, 3, 2]
[1, 3, 4]
[1, 4, 0]
[1, 4, 2]
[1, 4, 3]
[2, 0, 1]
[2, 0, 3]
[2, 0, 4]
[2, 1, 0]
[2, 1, 3]
[2, 1, 4]
[2, 3, 0]
[2, 3, 1]
[2, 3, 4]
[2, 4, 0]
[2, 4, 1]
[2, 4, 3]
[3, 0, 1]
[3, 0, 2]
[3, 0, 4]
[3, 1, 0]
[3, 1, 2]
[3, 1, 4]
[3, 2, 0]
[3, 2, 1]
[3, 2, 4]
[3, 4, 0]
[3, 4, 1]
[3, 4, 2]
[4, 0, 1]
[4, 0, 2]
[4, 0, 3]
[4, 1, 0]
[4, 1, 2]
[4, 1, 3]
[4, 2, 0]
[4, 2, 1]
[4, 2, 3]
[4, 3, 0]
[4, 3, 1]
[4, 3, 2]
组合:
[0, 1, 2]
[0, 1, 3]
[0, 1, 4]
[0, 2, 3]
[0, 2, 4]
[0, 3, 4]
[1, 2, 3]
[1, 2, 4]
[1, 3, 4]
[2, 3, 4]

原文地址:https://www.cnblogs.com/nocomment/p/13098495.html