主题:可重复组合问题
谁能解释一下这段代码,本人C++菜鸟,谢谢!
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <cassert>
using namespace std;
template <typename ElemType>
void CalcRepeatableCombination(const ElemType elements[], int num, int k,
vector<ElemType> &pre)
{
if (k == 1) {
for (int i = 0; i < num; ++i) {
copy(pre.begin(), pre.end(), ostream_iterator<ElemType>(cout));
cout << elements[i];
cout << endl;
}
return;
}
if (num == 1) {
ostream_iterator<ElemType> outIter(cout);
outIter = copy(pre.begin(), pre.end(), outIter);
fill_n(outIter, k, elements[0]);
cout << endl;
return;
}
pre.push_back(elements[0]);
CalcRepeatableCombination(elements, num, k - 1, pre);
pre.pop_back();
CalcRepeatableCombination(elements + 1, num - 1, k, pre);
}
template <typename ElemType>
void CalcRepeatableCombination(const ElemType elements[], int num, int k)
{
assert(num >= k && k >= 1);
vector<ElemType> one;
CalcRepeatableCombination(elements, num, k, one);
}
int main()
{
char elements[] = {'a', 'b', 'c', 'd'};
CalcRepeatableCombination(elements, 4, 3);
}
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <cassert>
using namespace std;
template <typename ElemType>
void CalcRepeatableCombination(const ElemType elements[], int num, int k,
vector<ElemType> &pre)
{
if (k == 1) {
for (int i = 0; i < num; ++i) {
copy(pre.begin(), pre.end(), ostream_iterator<ElemType>(cout));
cout << elements[i];
cout << endl;
}
return;
}
if (num == 1) {
ostream_iterator<ElemType> outIter(cout);
outIter = copy(pre.begin(), pre.end(), outIter);
fill_n(outIter, k, elements[0]);
cout << endl;
return;
}
pre.push_back(elements[0]);
CalcRepeatableCombination(elements, num, k - 1, pre);
pre.pop_back();
CalcRepeatableCombination(elements + 1, num - 1, k, pre);
}
template <typename ElemType>
void CalcRepeatableCombination(const ElemType elements[], int num, int k)
{
assert(num >= k && k >= 1);
vector<ElemType> one;
CalcRepeatableCombination(elements, num, k, one);
}
int main()
{
char elements[] = {'a', 'b', 'c', 'd'};
CalcRepeatableCombination(elements, 4, 3);
}