P26 (**) Generate the combinations of K distinct objects chosen from the N elements of a list.

问题描述

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个元素的组合,我们可以直接返回。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值