实现组合算法C(n,k),可以用递归实现:
import copy #实现list的深复制
def combine(lst, l):
result = []
tmp = [0]*l
length = len(lst)
def next_num(li=0, ni=0):
if ni == l:
result.append(copy.copy(tmp))
return
for lj in range(li,length):
tmp[ni] = lst[lj]
next_num(lj+1, ni+1)
next_num()
return result
实现排列算法A(n,k),用递归实现:
k=len(lst)s时,为全排列
import copy
def permutation(lst,k):
result = []
length = len(lst)
tmp = [0]*k
def next_num(a,ni=0):
if ni == k:
result.append(copy.copy(tmp))
return
for lj in a:
tmp[ni] = lj
b = a[:]
b.pop(a.index(lj))
next_num(b,ni+1)
c = lst[:]
next_num(c,0)
return result