今天从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