集合的子集构造算法

Scheme实现:

(define (subsets s)
  (define nil '())
  (if (null? s)
      (list nil)
      (let ((rest (subsets (cdr s))))
        (append rest (map (lambda (items)
                            (cons (car s) items))
                          rest)))))

; testing
(define set (list 1 2 3))

(display (subsets set))

 

c++实现:

template <typename ElemType>
vector<set<ElemType>> Subsets(vector<ElemType> elements)
{
  vector<set<ElemType>> result;

  result.push_back(set<ElemType>( ));
  for (int i = elements.size( ) - 1; i >= 0; --i) {
    auto result_copy = result;
    for (int j = result.size( ) - 1; j >= 0; --j) {
      set<ElemType> elem_copy = result[j];
      elem_copy.insert(elements[i]);
      result_copy.push_back(elem_copy);
    }
    result = result_copy;
  }
  return result;
}

 

test case:

int main( )
{
  vector<int> set = {1, 2, 3};

  auto result = Subsets(set);
  for each(auto elem in result) {
    for_each(elem.begin( ), elem.end( ), [] (int x){ std::cout << " " << x; });
    std::cout << std::endl;
  }

  return 0;
}
posted @ 2015-12-09 13:25  Leptus  阅读(681)  评论(0编辑  收藏  举报