我看大家都在说递归,我贴一个scheme的解答(很优美)(答案包括空子集)
;;; the given set
(define a-list (list 1 2 3 4))
;;; the function of subset of a list
(define (subset a-list)
(if (eq? a-list '())
(list '())
(append (subset (cdr a-list))
(map (lambda (x) (cons (car a-list) x))
(subset (cdr a-list))))))
;;; test
(subset a-list)
输出:
'(()
(4)
(3)
(3 4)
(2)
(2 4)
(2 3)
(2 3 4)
(1)
(1 4)
(1 3)
(1 3 4)
(1 2)
(1 2 4)
(1 2 3)
(1 2 3 4))