天天看點

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

組合算法

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

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

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

标簽:

版權申明:本站文章部分自網絡,如有侵權,請聯系:[email protected]

特别注意:本站所有轉載文章言論不代表本站觀點!

本站所提供的圖檔等素材,版權歸原作者所有,如需使用,請與原作者聯系。