# 从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;
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：从N个元素中取k个元素子集的c++实现 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)