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

來源:互聯網
上載者:User
組合演算法

本程式的思路是開一個數組,其下標表示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)) / 6for 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進

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

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

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.