#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
int main() {
const vector<int> set = { 0, 1, 2, 3 };
const auto k = 3;
vector<vector<int>::const_iterator> its(k, cbegin(set));
vector<bool> ns(k);
for(int i = k - 1; its.front() != cend(set); its[i] = next(its[i], ns[i] ? -1 : 1), i = k - 1) {
transform(cbegin(its), cend(its), ostream_iterator<int>(cout), [](const auto& i) { return *i; });
cout << endl;
while (i > 0 && (!ns[i] && its[i] == prev(cend(set)) || ns[i] && its[i] == cbegin(set))) {
ns[i] = !ns[i];
--i;
}
}
}
I2luY2x1ZGUgPGFsZ29yaXRobT4KI2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8aXRlcmF0b3I+CiNpbmNsdWRlIDx2ZWN0b3I+Cgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKaW50IG1haW4oKSB7Cgljb25zdCB2ZWN0b3I8aW50PiBzZXQgPSB7IDAsIDEsIDIsIDMgfTsKCWNvbnN0IGF1dG8gayA9IDM7CgoJdmVjdG9yPHZlY3RvcjxpbnQ+Ojpjb25zdF9pdGVyYXRvcj4gaXRzKGssIGNiZWdpbihzZXQpKTsKCXZlY3Rvcjxib29sPiBucyhrKTsKCglmb3IoaW50IGkgPSBrIC0gMTsgaXRzLmZyb250KCkgIT0gY2VuZChzZXQpOyBpdHNbaV0gPSBuZXh0KGl0c1tpXSwgbnNbaV0gPyAtMSA6IDEpLCBpID0gayAtIDEpIHsKCQl0cmFuc2Zvcm0oY2JlZ2luKGl0cyksIGNlbmQoaXRzKSwgb3N0cmVhbV9pdGVyYXRvcjxpbnQ+KGNvdXQpLCBbXShjb25zdCBhdXRvJiBpKSB7IHJldHVybiAqaTsgfSk7CgoJCWNvdXQgPDwgZW5kbDsKCgkJd2hpbGUgKGkgPiAwICYmICghbnNbaV0gJiYgaXRzW2ldID09IHByZXYoY2VuZChzZXQpKSB8fCBuc1tpXSAmJiBpdHNbaV0gPT0gY2JlZ2luKHNldCkpKSB7CgkJCW5zW2ldID0gIW5zW2ldOwoJCQktLWk7CgkJfQoJfQp9