fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <algorithm>
  4. using namespace std;
  5.  
  6. char x[100]; // Stores the current permutation
  7. int n;
  8. char c;
  9. string input; // Contains sorted letters from 'A' to c
  10. bool chuaxet[100]; // Tracks which characters are used
  11.  
  12. void Init() {
  13. cin >> c;
  14. input.resize(c - 'A' + 1);
  15. for (int i = 0; i <= c - 'A'; i++) {
  16. input[i] = 'A' + i;
  17. }
  18. sort(input.begin(), input.end());
  19. fill(chuaxet, chuaxet + input.size(), true);
  20. }
  21.  
  22. // Checks if the current permutation (x) is valid
  23. bool isValidPermutation(int len) {
  24. for (int i = 0; i < len - 1; i++) {
  25. if ((x[i] == 'A' && x[i + 1] == 'E') ||
  26. (x[i] == 'E' && x[i + 1] == 'A')) {
  27. return false;
  28. }
  29. }
  30. return true;
  31. }
  32.  
  33. void backtrack(int i) {
  34. if (i == input.size()) {
  35. // Print the permutation if valid
  36. if (isValidPermutation(i)) {
  37. for (int k = 0; k < i; k++) cout << x[k];
  38. cout << endl;
  39. }
  40. return;
  41. }
  42.  
  43. for (int j = 0; j < input.size(); j++) {
  44. if (chuaxet[j]) {
  45. x[i] = input[j]; // Choose input[j] for position i
  46. chuaxet[j] = false; // Mark as used
  47. backtrack(i + 1); // Recurse
  48. chuaxet[j] = true; // Backtrack (unmark)
  49. }
  50. }
  51. }
  52.  
  53. int main() {
  54. Init();
  55. backtrack(0);
  56. return 0;
  57. }
Success #stdin #stdout 0.01s 5288KB
stdin
D
stdout
ABCD
ABDC
ACBD
ACDB
ADBC
ADCB
BACD
BADC
BCAD
BCDA
BDAC
BDCA
CABD
CADB
CBAD
CBDA
CDAB
CDBA
DABC
DACB
DBAC
DBCA
DCAB
DCBA