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 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
| #include <vector> #include <iostream> #include <unordered_set>
using std::cout; using std::endl; using std::unordered_set; using std::vector;
class CPermutation { public: CPermutation(const int &n, const int &m) : n(n), m(m), flags(0), curPerm(0), permCount(0) {}
bool next() { if (this->curPerm.empty() == true) { for (int i = 0; i < this->m; ++i) { this->curPerm.push_back(i); this->flags.insert(i); }
++this->permCount; return true; }
int curPos = this->m - 1; int curMax = 0; while (curPos >= 0) { for (int i = this->n - 1; i >= 0; --i) { if (flags.find(i) == flags.end()) { curMax = i; break; } }
if (this->curPerm.at(curPos) >= curMax) { flags.erase(this->curPerm.at(curPos)); --curPos; } else { break; } }
if (curPos < 0) { return false; }
for (int i = this->curPerm.at(curPos); i < this->n; ++i) { if (flags.find(i) == flags.end()) { this->flags.erase(this->curPerm.at(curPos)); this->curPerm.at(curPos) = i; this->flags.insert(i); break; } }
for (const int p : this->curPerm) { flags.insert(p); }
for (int i = curPos + 1; i < this->m; ++i) { for (int j = 0; j < this->n; ++j) { if (flags.find(j) == flags.end()) { this->flags.erase(this->curPerm.at(i)); this->curPerm.at(i) = j; this->flags.insert(j); break; } } }
++this->permCount; return true; }
inline void printCurPerm() { for (const int p : this->curPerm) { cout << p << " "; } cout << endl; }
inline void printPermCount() { cout << this->permCount << endl; }
private: const int n; const int m;
vector<int> curPerm; unordered_set<int> flags; int permCount; };
int main() { const int n = 5; const int m = 3; CPermutation perm(n, m);
while (perm.next()) { perm.printCurPerm(); } perm.printPermCount();
return 0; }
|