Skip to content

Instantly share code, notes, and snippets.

Created Dec 7, 2010
What would you like to do?
Simple code to show how to create combinations with repetitions in C++
#include <algorithm>
#include <cassert>
#include <iostream>
#include <vector>
using std::copy;
using std::cout;
using std::endl;
using std::vector;
void combinations_r_recursive(const vector<char> &elems, unsigned long req_len,
vector<unsigned long> &pos, unsigned long depth,
unsigned long margin)
// Have we selected the number of required elements?
if (depth >= req_len) {
for (unsigned long ii = 0; ii < pos.size(); ++ii)
cout << elems[pos[ii]];
cout << endl;
// Try to select new elements to the right of the last selected one.
for (unsigned long ii = margin; ii < elems.size(); ++ii) {
pos[depth] = ii;
combinations_r_recursive(elems, req_len, pos, depth + 1, ii);
void combinations_r(const vector<char> &elems, unsigned long req_len)
assert(req_len > 0 && req_len <= elems.size());
vector<unsigned long> positions(req_len, 0);
combinations_r_recursive(elems, req_len, positions, 0, 0);
const unsigned long num_elements = 5;
const unsigned long comb_len = 3;
int main()
vector<char> elements(num_elements);
char elements_str[num_elements + 1] = "abcde";
copy(elements_str, elements_str + num_elements, elements.begin());
combinations_r(elements, comb_len);
return 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment