您的位置:首页 > 其它

排列组合算法之三: 递归法

2015-06-04 18:02 344 查看
a. 首先从n个数中选取编号最大的数,然后在剩下的n-1个数里面选取m-1个数,直到从n-(m-1)个数中选取1个数为止。

b. 从n个数中选取编号次小的一个数,继续执行1步,直到当前可选编号最大的数为m。

void zuheRecursive ( int a[], int n, int m, int b[], const int M )
{
for(int i=n; i>=m; i--) // 注意这里的循环范围
{
b[m-1] = i - 1;
if (m > 1)
zuheRecursive(a,i-1,m-1,b,M);
else // m == 1, 输出一个组合
{
for(int j=M-1; j>=0; j--)
cout << a[b[j]] << " ";
cout << endl;
}
}
}

递归封装
class ZuheRecursive
{
public:
typedef std::vector<std::vector<int> > TZuheResult;

ZuheRecursive(int srcLen, int m)
{
int * tmp = new int[m]();
zuheRecursive(srcLen, m, tmp, m);
delete [] tmp;
}

static void example()
{
int a[] = { 1, 2, 3, 4, 5 }; // 整数数组
int m = 3; // 待取出组合的个数
ZuheRecursive zuhe(5, m);
printZuheResult(a, zuhe.m_zuheCalculation);
}

// 打印组合结果
static void printZuheResult(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:
void zuheRecursive (int n, int m, int tempArrayLenM[], const int M)
{
for(int i=n; i>=m; i--) // 注意这里的循环范围
{
tempArrayLenM[m-1] = i - 1;
if (m > 1)
zuheRecursive(i-1,m-1,tempArrayLenM,M);
else // m == 1, 输出一个组合
{
std::vector<int> idxVector(tempArrayLenM, tempArrayLenM + M );
m_zuheCalculation.push_back(idxVector);
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: