zoukankan      html  css  js  c++  java
  • 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]

  • 相关阅读:
    安卓下拉,刷新
    Android继承AppCompatActivity实现全屏设置
    端口被占用:android studio 虚拟机adb.exe已停止工作的处理
    学习笔记
    github上的文件比对
    框架:提供一定能力的小段程序
    游戏中实现粒子碰撞,纯java
    一个仿3D的平面游戏页面
    多媒体流处理,安卓进阶之路
    空间主页播放任意FLV格式视频方法
  • 原文地址:https://www.cnblogs.com/nocomment/p/13098495.html
Copyright © 2011-2022 走看看