Implement combinations of a string on length N, with K letters chosen at a time (N>K). Eg: The combination of string "abc" with 2 letters chosen at a time is - ab, ac, bc
/*
* StringCombinationWithSize.cpp
*
* Created on: Apr 18, 2012
* Author: Kiran Hegde
*/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void combine(string prefix, string rest, unsigned int k, vector<string> &output) {
if (rest.size() < k)
return;
if (k == 0)
output.push_back(prefix);
for (unsigned int i=0; i<rest.size(); i++) {
combine(prefix + rest[i], rest.substr(i+1), k-1, output);
}
}
/**
* Test the function
*/
int main() {
string input("abc");
vector<string> combs;
combine("", input, 2, combs); // choose 2 at a time
cout << "Combinations: " << combs.size() << endl;
for (unsigned int i=0; i<combs.size(); i++) {
cout << combs[i] << endl;
}
}