fork download
  1. // C program to print all permutations with duplicates allowed
  2. #include <stdio.h>
  3. #include <string.h>
  4.  
  5. /* Function to swap values at two pointers */
  6. void swap(char *x, char *y)
  7. {
  8. char temp;
  9. temp = *x;
  10. *x = *y;
  11. *y = temp;
  12. }
  13.  
  14. /* Function to print permutations of string
  15. This function takes three parameters:
  16. 1. String
  17. 2. Starting index of the string
  18. 3. Ending index of the string. */
  19. void permute(char *a, int l, int r)
  20. {
  21. int i;
  22. if (l == r)
  23. printf("%s\n", a);
  24. else
  25. {
  26. for (i = l; i <= r; i++)
  27. {
  28. if (a[i] == a[l]) {
  29. continue;
  30. }
  31. swap((a+l), (a+i));
  32. permute(a, l+1, r);
  33. swap((a+l), (a+i)); //backtrack
  34. }
  35. }
  36. }
  37.  
  38. /* Driver program to test above functions */
  39. int main()
  40. {
  41. char str[] = "AABC";
  42. int n = strlen(str);
  43. permute(str, 0, n-1);
  44. return 0;
  45. }
  46.  
Success #stdin #stdout 0s 4560KB
stdin
Standard input is empty
stdout
AABC
AACB
ABAC
ABCA
ACBA
ACAB
AABC
AACB
ABAC
ABCA
ACBA
ACAB
BAAC
BACA
BAAC
BACA
BCAA
BCAA
CABA
CAAB
CBAA
CBAA
CABA
CAAB