組合算法
本程序的思路是開一個數組,其下標表示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 iin 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進
一。每加一次一就判斷一下各位數組單元有無重複,有則再轉回去做加一操作,沒
有則說明得到了一個排列方案。