Skip to content

Instantly share code, notes, and snippets.

@loromits
Created October 12, 2018 19:46
Show Gist options
  • Save loromits/82b2d4b736e9cbd56d42cb738d8b32e1 to your computer and use it in GitHub Desktop.
Save loromits/82b2d4b736e9cbd56d42cb738d8b32e1 to your computer and use it in GitHub Desktop.
Outputs all non-empty combinations for given number. `assert(n > 0)`
#include <iostream>
#include <vector>
#include <numeric>
bool lift(std::vector<int>& vec, int limit) {
if (vec.back() < limit) {
vec.back() += 1;
return true;
}
for (auto rit = std::next(vec.rbegin()); rit != vec.rend(); rit++) {
if (*rit + 1 < *std::prev(rit)) {
*rit += 1;
return true;
}
}
return false;
}
int main() {
int n;
std::cin >> n;
for (int k = 1; k < n + 1; ++k) {
std::vector<int> vec(k);
std::iota(vec.begin(), vec.end(), 1);
do {
std::cout << k;
for (auto el: vec) {
std::cout << " " << el;
}
std::cout << std::endl;
} while (lift(vec, n));
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment