从N个元素中取k个元素子集的c++实现

#include <iostream>
#include <vector>

using namespace std;

int C( int n, int m)           //计算组合数
  {
    if ( n == 0 )
      return 1;
    int res = 1;
    int temp = m - n;
    for( int i = m; i != temp; --i )
      res *= i;
    for( int j = n; j > 1; --j )
      res /= j;
    return res;
  }

int main()
  {
        const int N = 8;
        int Array[] = { 1, 2, 3, 4, 5, 6 ,7 ,8 };
        //cout << "Please enter the array" << endl;
        //for (int i1 = 0; i1 < N; cin >> Array[i1++]);
        //for( int a = 0; a < N; ++a )
                //cout << Array[a] << endl;
        cout << "Please input K" << endl;
        int K;
        cin >> K;
        int num = C( K, N );
        vector< vector<int> > ivec(num);        //K个元素子集的个数
        vector< vector<int> >::iterator it;
        vector< vector<int>  >::size_type index = 0;

        //先存储第一列数
        for( int i = 0; i <= N - K; ++i )
          for( int j = 0; j < C( K - 1, N - i - 1 ); ++j )
            ivec[index++].push_back( Array[i] );
        for( int k = 1; k < K; ++k )
          {
            index = 0;        
            for( int i = k; index < ivec.size(); ++i )
            {
              for( int j = 0; j < C( K - k - 1, N - i -1 ); ++j )
                ivec[index++].push_back( Array[i] );
              if( i == N - K + k && index < ivec.size() )
                i =  ivec[index][k - 1] - 1;
            }        
          }
       
        cout << "Here is the result !" << endl;
        cout << "There are "
             << ivec.size()
             << " subarray"
             << endl;
        for( it = ivec.begin(); it != ivec.end(); ++it )
        {
          for( vector<int>::iterator it1 = (*it).begin(); it1 != (*it).end(); ++it1 )
              cout << *it1;
          ( it + 1 - ivec.begin()) % 10 ? cout << " " : cout << endl;
        }

        return 0;
}

这是算法设计与分析的一道作业题,基本思路是通过想实现的结果发现每一个数出现的次数都跟组合数有一定的关系,并根据这种关系将子集存放在一个二维vector里。 


 

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭