#include <algorithm> #include <functional> #include <iostream> #include <vector> void permutationUtilInner(std::vector<int> v, std::function<void (const std::vector<int>&)> f) { do { f(v); } while (std::next_permutation(v.begin(), v.end())); } void permutationUtil(std::vector<int> v, std::size_t r, std::function<void (const std::vector<int>&)> f) { std::vector<bool> b(v.size() - r, false); b.resize(v.size(), true); std::sort(v.begin(), v.end()); do { std::vector<int> sub; for (std::size_t i = 0; i != b.size(); ++i) { if (b[i]) { sub.push_back(v[i]); } } permutationUtilInner(sub, f); } while (std::next_permutation(b.begin(), b.end())); } void print_vector(const std::vector<int>& v) { const char* sep = ""; std::cout << '{'; for (const auto e : v) { std::cout << sep << e; sep = ", "; } std::cout << "}\n"; } int main() { permutationUtil({1, 2, 3, 4}, 3, &print_vector); }
Standard input is empty
{2, 3, 4} {2, 4, 3} {3, 2, 4} {3, 4, 2} {4, 2, 3} {4, 3, 2} {1, 3, 4} {1, 4, 3} {3, 1, 4} {3, 4, 1} {4, 1, 3} {4, 3, 1} {1, 2, 4} {1, 4, 2} {2, 1, 4} {2, 4, 1} {4, 1, 2} {4, 2, 1} {1, 2, 3} {1, 3, 2} {2, 1, 3} {2, 3, 1} {3, 1, 2} {3, 2, 1}