fork download
  1. // Function to swap two characters
  2. void swap(char *x, char *y) {
  3. char temp = *x;
  4. *x = *y;
  5. *y = temp;
  6. }
  7.  
  8. // Function to print all permutations of the string
  9. void permute(char *str, int l, int r) {
  10. if (l == r) {
  11. printf("%s ", str); // Print the permutation
  12. } else {
  13. for (int i = l; i <= r; i++) {
  14. swap(&str[l], &str[i]); // Swap characters
  15. permute(str, l + 1, r); // Recur for the next character
  16. swap(&str[l], &str[i]); // Backtrack
  17. }
  18. }
  19. }
  20.  
  21. int main() {
  22. int T;
  23. scanf("%d", &T); // Number of test cases
  24.  
  25. // Process each test case
  26. for (int t = 0; t < T; t++) {
  27. char s[6]; // String size is at most 5, so array size 6
  28. scanf("%s", s);
  29.  
  30. // Sort the string to ensure lexicographical order
  31. int len = strlen(s);
  32. // Simple sorting logic
  33. for (int i = 0; i < len-1; i++) {
  34. for (int j = i+1; j < len; j++) {
  35. if (s[i] > s[j]) {
  36. swap(&s[i], &s[j]);
  37. }
  38. }
  39. }
  40.  
  41. permute(s, 0, len - 1); // Call permute to generate all permutations
  42. printf("\n"); // Print a new line after all permutations
  43. }
  44.  
  45. return 0;
  46. }
  47.  
Success #stdin #stdout 0s 5288KB
stdin
2
acb
sad
stdout
abc acb bac bca cba cab 
ads asd das dsa sda sad