fork download
  1. #include <iostream>
  2.  
  3. void backtrack(int p, int n, char* trace, int* avail) {
  4. if (p == n) {
  5. std::cout << trace << '\n';
  6. return;
  7. }
  8. for (int i = 255; i >= 0; --i) {
  9. if (avail[i] > 0) {
  10. trace[p] = 127 - i;
  11. avail[i]--;
  12. backtrack(p+1, n, trace, avail);
  13. avail[i]++;
  14. }
  15. }
  16. }
  17.  
  18. void permuteString(int n, char* str) {
  19. char* trace = new char[n+1]();
  20. int* avail = new int[256]();
  21. for (int i = 0; i < n; ++i) {
  22. avail[127 - str[i]]++;
  23. }
  24. backtrack(0, n, trace, avail);
  25. delete[] avail;
  26. delete[] trace;
  27. }
  28.  
  29. int main() {
  30. int n;
  31. char* str;
  32. std::cout << "Enter n: ";
  33. std::cin >> n;
  34. str = new char[n+1]();
  35. std::cout << "Enter string: ";
  36. std::cin.ignore(1000, '\n');
  37. std::cin.get(str, n+1, '\n');
  38.  
  39. permuteString(n, str);
  40.  
  41. delete[] str;
  42.  
  43. return 0;
  44. }
Success #stdin #stdout 0.01s 5452KB
stdin
6
aabbcc
stdout
Enter n: Enter string: aabbcc
aabcbc
aabccb
aacbbc
aacbcb
aaccbb
ababcc
abacbc
abaccb
abbacc
abbcac
abbcca
abcabc
abcacb
abcbac
abcbca
abccab
abccba
acabbc
acabcb
acacbb
acbabc
acbacb
acbbac
acbbca
acbcab
acbcba
accabb
accbab
accbba
baabcc
baacbc
baaccb
babacc
babcac
babcca
bacabc
bacacb
bacbac
bacbca
baccab
baccba
bbaacc
bbacac
bbacca
bbcaac
bbcaca
bbccaa
bcaabc
bcaacb
bcabac
bcabca
bcacab
bcacba
bcbaac
bcbaca
bcbcaa
bccaab
bccaba
bccbaa
caabbc
caabcb
caacbb
cababc
cabacb
cabbac
cabbca
cabcab
cabcba
cacabb
cacbab
cacbba
cbaabc
cbaacb
cbabac
cbabca
cbacab
cbacba
cbbaac
cbbaca
cbbcaa
cbcaab
cbcaba
cbcbaa
ccaabb
ccabab
ccabba
ccbaab
ccbaba
ccbbaa