實現組合算法C(n,k),可以用遞歸實現:
python代碼:
1 import copy #實現list的深復制 2 3 def combine(lst, l): 4 result = [] 5 tmp = [0]*l 6 length = len(lst) 7 def next_num(li=0, ni=0): 8 if ni == l: 9 result.append(copy.copy(tmp)) 10 return 11 for lj in range(li,length): 12 tmp[ni] = lst[lj] 13 next_num(lj+1, ni+1) 14 next_num() 15 return result
實現排列算法A(n,k),用遞歸實現:
k=len(lst)s時,為全排列
1 import copy 2 3 def permutation(lst,k): 4 result = [] 5 length = len(lst) 6 tmp = [0]*k 7 def next_num(a,ni=0): 8 if ni == k: 9 result.append(copy.copy(tmp)) 10 return 11 for lj in a: 12 tmp[ni] = lj 13 b = a[:] 14 b.pop(a.index(lj)) 15 next_num(b,ni+1) 16 c = lst[:] 17 next_num(c,0) 18 return result
