組合算法
本程序的思路是開一個數組,其下標表示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)
方法二:
charters = ['A', 'B', 'C', 'D', 'E', 'F'] s4 = time.time() group = [1, 1, 1, 0, 0, 0] group_len = len(group) ret_num = (group_len * (group_len - 1) * (group_len - 2)) / 6 #記錄 group 的1位置的容器 indexes = [0, 1, 2] for i in xrange(ret_num - 1): ''' 第一步:先把10換成01 第二步:把第一個10前面的所有1放在數組的最左邊 ''' tmp = [] #location:第一個10的起始位置 #如果 indexes 的第一個元素與第二個元素值不連續,那么說明 group 的第一個10在最左邊 #[tmp.append(charters[i]) for i in indexes] tmp.append(charters[indexes[0]]) tmp.append(charters[indexes[1]]) tmp.append(charters[indexes[2]]) print tmp if indexes[0] + 1 < indexes[1]: location = indexes[0] indexes[0] = location + 1 #如果 indexes 的第二個元素與第三個元素值不連續,那么說明 group 的第一個10在中間 elif indexes[1] + 1 < indexes[2]: location = indexes[1] indexes[1] = location + 1 # indexes 中間的1進位之后,把左邊的1的位置記錄為0,同時修改 group 相應位置的值 group[indexes[1] - 1] = 0 group[0] = 1 indexes[0] = 0 #如果 indexes 的三個元素值都是連續的,那么說明 group 的第一個10在最右邊 elif indexes[0] + 1 == indexes[1] and indexes[1] + 1 == indexes[2]: location = indexes[2] indexes[2] = location + 1 group[indexes[0]] = 0 group[indexes[1]] = 0 group[0] = 1 group[1] = 1 indexes[0] = 0 indexes[1] = 1 if location < 5: group[location] = 0 group[location + 1] = 1 else: group[location] = 1 print time.time() - s4,'*************' #print ret,'**********'
第二種方法經過優化,效率相當高。測試了1600多億的循環計算,方法一要22分鍾,而方法二只需要1分鍾。
全排列算法
從1到N,輸出全排列,共N!條。
分析:用N進制的方法吧。設一個N個單元的數組,對第一個單元做加一操作,滿N進
一。每加一次一就判斷一下各位數組單元有無重復,有則再轉回去做加一操作,沒
有則說明得到了一個排列方案。