void permute(string elems, int mid, int end)
{
static int count;
if (mid == end) {
cout << ++count << \" : \" << elems << end
Any algorithm for generating permutations is going to run in polynomial time, because the number of permutations for characters within an n-length string is (n!)
. That said, there are some pretty simple in-place algorithms for generating permutations. Check out the Johnson-Trotter algorithm.
Here is a non-recursive algorithm in C++ from the Wikipedia entry for unordered generation of permutations. For the string s
of length n
, for any k
from 0
to n! - 1
inclusive, the following modifies s
to provide a unique permutation (that is, different from those generated for any other k value on that range). To generate all permutations, run it for all n! k
values on the original value of s.
#include <algorithm>
void permutation(int k, string &s)
{
for(int j = 1; j < s.size(); ++j)
{
std::swap(s[k % (j + 1)], s[j]);
k = k / (j + 1);
}
}
Here swap(s, i, j)
swaps position i and j of the string s.