Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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; 
}
share|improve this question
Doesn't seem to work. Firstly, the strings are not in lexicographically sorted order, and secondly there are repetitions - eg if string = "AAA", it prints "AAA" 27 times when there is really only 1 permutation. Or did I misunderstand the objective? Also should string s be const string& s ? – William Morris Oct 23 '12 at 17:52
@WilliamMorris, for the case "AAA", it's OK to print 27 times. You're right, the strings are not in lexicographically sorted order. I should sort the string at first. Thanks very much – FihopZz Oct 24 '12 at 0:17
Removed the C tag, as this is clearly C++. – harald Mar 6 at 23:05

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.