今天從infoq看到一個算法題,於是用python(最近一年改用python做項目了)實現了一下。
比如“1,2,3....10”,1到10這10個數,顯示他的所有可能組合情況(排列順序無所謂)
1 # -*- coding: utf-8 -*- 2 #!/usr/local/bin/python 3 4 Count = 0 5 def combination(data, t, vl): 6 _kk = len(data) 7 for _i in range(_kk-t+1): 8 vl.append(data[_i]) 9 new_data = data[_i+1:] 10 if t-1 == 1: 11 for _j in range(len(new_data)): 12 print ','.join(map(str,vl))+','+str(new_data[_j]) 13 global Count 14 Count += 1 15 else: 16 combination(new_data, t-1, vl) 17 vl.pop() 18 19 if __name__ == '__main__': 20 n = 10 # 總數 21 t = 6 # 選取個數 22 vl = [] # 用於存放選中的數字 23 data = range(1, n+1)#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 24 combination(data, t, vl) 25 _count_correct = reduce(lambda x, y: x*y,range(n,n-t,-1)) / reduce(lambda x, y: x*y,range(t,0,-1)) 26 print Count, Count == _count_correct