void permute(string elems, int mid, int end)
{
static int count;
if (mid == end) {
cout << ++count << \" : \" << elems << end
Here yet another recursive function for string permutations:
void permute(string prefix, string suffix, vector &res) {
if (suffix.size() < 1) {
res.push_back(prefix);
return;
}
for (size_t i = 0; i < suffix.size(); i++) {
permute(prefix + suffix[i], suffix.substr(0,i) + suffix.substr(i + 1), res);
}
}
int main(){
string str = "123";
vector res;
permute("", str, res);
}
The function collects all permutations in vector res. The idea can be generalized for different type of containers using templates and iterators:
template
void permute(typename Cont1_t prefix,
typename Cont1_t::iterator beg, typename Cont1_t::iterator end,
Cont2_t &result)
{
if (beg == end) {
result.insert(result.end(), prefix);
return;
}
for (auto it = beg; it != end; ++it) {
prefix.insert(prefix.end(), *it);
Cont1_t tmp;
for (auto i = beg; i != end; ++i)
if (i != it)
tmp.insert(tmp.end(), *i);
permute(prefix, tmp.begin(), tmp.end(), result);
prefix.erase(std::prev(prefix.end()));
}
}
int main()
{
string str = "123";
vector rStr;
permute>("", str.begin(), str.end(), rStr);
vectorvint = { 1,2,3 };
vector> rInt;
permute, vector>>({}, vint.begin(), vint.end(), rInt);
list ll = { 1,2,3 };
vector> vlist;
permute, vector>>({}, ll.begin(), ll.end(), vlist);
}
This may be an interesting programming exercise, but in production code you should use a non recusrive version of permutation , like next_permutation.