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