http://blog.csdn.net/canguanxihu/article/details/46363375
class ZuheAssistArray
{
public:
typedef std::vector<std::vector<int> > TZuheResult;
ZuheAssistArray(int srcLen, int m)
{
int n = srcLen; //C(n,m)
// 生成辅助数组。首先初始化,将数组前m个元素置1,表示第一个组合为前m个数。
std::vector<int> tempNum(srcLen, 0);
for(int i = 0; i < m; ++i)
{
tempNum[i] = 1;
}
std::vector<int> oneof;
m_zuheCalculation.push_back(createResult(tempNum, n, oneof));// 打印第一个默认组合
// 然后从左到右扫描数组元素值的“10”组合,找到第一个“10”组合后将其变为“01”
for (int i = 0; i < n - 1; i++)
{
if (tempNum[i] == 1 && tempNum[i + 1] == 0)
{
tempNum[i] = 0;
tempNum[i + 1] = 1;
std::sort(tempNum.begin(), tempNum.begin() + i, compare);
m_zuheCalculation.push_back(createResult(tempNum, n, oneof));
i = 0;
continue;
}
}
// 不判断是否为最后一个组合:计算结束时,不再有10组合
}
static bool compare(int a, int b){
if(a > b){
return true;
}else{
return false;
}
}
//使用举例函数
static void example()
{
int a[] = { 1, 2, 3, 4, 5 }; // 整数数组
int m = 3; // 待取出组合的个数
ZuheAssistArray zuhe(5, m);
printZuheResult(a, zuhe.m_zuheCalculation);
}
// 打印组合结果
static void printZuheResult(const int src[], TZuheResult zhr)
{
for (auto it = zhr.begin(); it != zhr.end(); it++)
{
for (auto itEle = it->begin(); itEle != it->end(); itEle++)
{
cout << src[*itEle] << " ";
}
cout << std::endl;
}
}
public:
TZuheResult m_zuheCalculation;
private:
// 根据辅助数组和原始数组生成 结果数组
std::vector<int> & createResult(const std::vector<int>& assist,
const int srcLen, std::vector<int> &dst)
{
dst.clear();
for (int i = 0; i < srcLen; i++)
{
if (assist[i] == 1)
{
dst.push_back(i);
}
}
return dst;
}
};