Skip to main content
edited tags
Link
harald
  • 696
  • 5
  • 12
Tweeted twitter.com/#!/StackCodeReview/status/260939151615074304
added 380 characters in body
Source Link
Fihop
  • 1k
  • 4
  • 20
  • 31

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(stringconst 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; } 

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(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); } } 

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; } 
Source Link
Fihop
  • 1k
  • 4
  • 20
  • 31
Loading