问题描述
In how many ways can a committee of 3 be chosen from a group of 12 people? We all know that there are C(12,3) = 220 possibilities (C(N,K) denotes the well-known binomial coefficients). For pure mathematicians, this result may be great. But we want to really generate all the possibilities in a list.
sash> (combination 3 '(a b c d e f))
-> ((a b c) (a b d) (a b e) ... )
解法
(define combination
(lambda (K ls)
(letrec ([comb (lambda (s i one) (if (= i K) (list (reverse one)) (let loop ([s s]) (if (null? s) '() (append (comb (cdr s) (+ i 1) (cons (car s) one)) (loop (cdr s)))))))])
(comb ls 0 '()))))
one
变量保存一个组合,比如(2 1)
。
生成one
的结束条件用了(null? s)
判断,还可以进行优化。因为如果末尾的元素数量不足以生成r个元素的组合,我们可以直接返回。