Given a string of length n, print all permutation of the given string. Repetition of characters is allowed. Print these permutations in lexicographically sorted order
Examples:
Input: AB
Ouput: All permutations of AB with repetition are:
AA
AB
BA
BB
Input: ABC
Output: All permutations of ABC with repetition are:
AAA
AAB
AAC
ABA
...
...
CCB
CCC
The following is my code:
void permutate(const string& s, int* index, int depth, int len, int& count)
{
if(depth == len)
{
++count;
for(int i = 0; i < len; ++i)
{
cout << s[index[i]];
}
cout << endl;
return;
}
for(int i = 0; i < len; ++i)
{
index[depth] = i;
permutate(s, index, depth+1, len, count);
}
}
int main()
{
string s("CBA");
sort(s.begin(), s.end());
cout << s << endl;
cout << "**********" << endl;
int len = s.size();
int* index = new int[len];
int count = 0;
permutate(s, index, 0, len, count);
cout << count << endl;
system("pause");
return 0;
}
string
= "AAA", it prints "AAA" 27 times when there is really only 1 permutation. Or did I misunderstand the objective? Also shouldstring s
beconst string& s
? \$\endgroup\$