1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| #include <vector> #include <iostream>
using std::cout; using std::endl; using std::vector;
class CCombination { public: CCombination(const int &n, const int &m) : n(n), m(m), curComb(0), combCount(0) {}
bool next() { if (this->curComb.empty() == true) { for (int i = 0; i < this->m; ++i) { this->curComb.push_back(i); }
++this->combCount; return true; }
int curPos = this->m - 1; while ((curPos >= 0) && (this->curComb.at(curPos) == this->n - this->m + curPos)) { --curPos; }
if (curPos < 0) { return false; }
++this->curComb.at(curPos);
for (int right = curPos + 1; right < this->m; ++right) { this->curComb.at(right) = this->curComb.at(right - 1) + 1; }
++this->combCount; return true; }
inline void printCurComb() { for (const int c : this->curComb) { cout << c << " "; } cout << endl; }
inline void printCombCount() { cout << this->combCount << endl; }
private: const int n; const int m;
vector<int> curComb; int combCount; };
int main() { const int n = 5; const int m = 3; CCombination comb(n, m);
while (comb.next()) { comb.printCurComb(); } comb.printCombCount();
return 0; }
|