python實現高效率的排列組合算法

ybw8 9年前發布 | 2K 次閱讀 Python

組合算法 本程序的思路是開一個數組,其下標表示1到m個數,數組元素的值為1表示其下標 代表的數被選中,為0則沒選中。 首先...

組合算法  

 本程序的思路是開一個數組,其下標表示1到m個數,數組元素的值為1表示其下標  

 代表的數被選中,為0則沒選中。    

 首先初始化,將數組前n個元素置1,表示第一個組合為前n個數。    

 然后從左到右掃描數組元素值的“10”組合,找到第一個“10”組合后將其變為  

 “01”組合,同時將其左邊的所有“1”全部移動到數組的最左端。    

 當第一個“1”移動到數組的m-n的位置,即n個“1”全部移動到最右端時,就得  

 到了最后一個組合。    

 例如求5中選3的組合:    

 1   1   1   0   0   //1,2,3    

 1   1   0   1   0   //1,2,4    

 1   0   1   1   0   //1,3,4    

 0   1   1   1   0   //2,3,4    

 1   1   0   0   1   //1,2,5    

 1   0   1   0   1   //1,3,5    

 0   1   1   0   1   //2,3,5    

 1   0   0   1   1   //1,4,5    

 0   1   0   1   1   //2,4,5    

 0   0   1   1   1   //3,4,5  


使用python實現:

group = [1, 1, 1, 0, 0, 0]
group_len = len(group)
#計算次數
ret = [group]
ret_num = (group_len * (group_len - 1) * (group_len - 2)) / 6
for i in xrange(ret_num - 1):

    '第一步:先把10換成01'
    number1_loc = group.index(1)
    number0_loc = group.index(0)

    #替換位置從第一個0的位置開始
    location = number0_loc
      #判斷第一個0和第一個1的位置哪個在前,
      #如果第一個0的位置小于第一個1的位置,
      #那么替換位置從第一個1位置后面找起

    if number0_loc < number1_loc:
        location = group[number1_loc:].index(0) + number1_loc

    group[location] = 1
    group[location - 1] = 0

    '第二步:把第一個10前面的所有1放在數組的最左邊'
    if location - 3 >= 0:
        if group[location - 3] == 1 and group[location - 2] == 1:
            group[location - 3] = 0
            group[location - 2] = 0
            group[0] = 1
            group[1] = 1
        elif group[location - 3] == 1:
            group[location - 3] = 0
            group[0] = 1
        elif group[location - 2] == 1:
            group[location - 2] = 0
            group[0] = 1

    print group
    ret.append(group)


全排列算法  

從1到N,輸出全排列,共N!條。  

分析:用N進制的方法吧。設一個N個單元的數組,對第一個單元做加一操作,滿N進  

一。每加一次一就判斷一下各位數組單元有無重復,有則再轉回去做加一操作,沒  

有則說明得到了一個排列方案。


 本文由用戶 ybw8 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!