fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. /* Function to swap values at two pointers */
  5. void swap(char *x, char *y)
  6. {
  7. char temp;
  8. temp = *x;
  9. *x = *y;
  10. *y = temp;
  11. }
  12.  
  13. /* Function to print permutations of string
  14.   This function takes three parameters:
  15.   1. String
  16.   2. Starting index of the string
  17.   3. Ending index of the string. */
  18. void permute(char *a, int l, int r)
  19. {
  20. int i;
  21. if (l != r)
  22. {
  23. for (i = l; i <= r; i++)
  24. {
  25. swap((a+l), (a+i));
  26. permute(a, l+1, r);
  27. swap((a+l), (a+i)); //backtrack
  28. }
  29. }
  30. else
  31. {
  32. printf("%s\n", a);
  33. }
  34. }
  35.  
  36. /* arr[] ---> Input Array
  37.   data[] ---> Temporary array to store current combination
  38.   start & end ---> Staring and Ending indexes in arr[]
  39.   index ---> Current index in data[]
  40.   r ---> Size of a combination to be printed */
  41. void combinationUtil(char alphas[], char data[], int start, int end,
  42. int index, int count)
  43. {
  44. int i;
  45. if (index == count)
  46. {
  47. data[count] = '\0';
  48. permute(data, 0, count-1);
  49. return;
  50. }
  51.  
  52. for (i=start; i<=end && end-i+1 >= count-index; i++)
  53. {
  54. data[index] = alphas[i];
  55. combinationUtil(alphas, data, i+1, end, index+1, count);
  56. }
  57. }
  58.  
  59. // The main function that prints all combinations of size r
  60. // in arr[] of size n. This function mainly uses combinationUtil()
  61. void printCombination(char alphas[], int n, int count)
  62. {
  63. int data[count+1];
  64. combinationUtil(alphas, data, 0, n-1, 0, count);
  65. }
  66.  
  67. int main()
  68. {
  69. char alphas[] = "ABCD";
  70. int i;
  71. int len = strlen(alphas);
  72. for(i = 0; i<len; i++)
  73. printCombination(alphas, len, i+1);
  74. return 0;
  75. }
  76.  
Success #stdin #stdout 0s 10320KB
stdin
Standard input is empty
stdout
A
B
C
D
AB
BA
AC
CA
AD
DA
BC
CB
BD
DB
CD
DC
ABC
ACB
BAC
BCA
CBA
CAB
ABD
ADB
BAD
BDA
DBA
DAB
ACD
ADC
CAD
CDA
DCA
DAC
BCD
BDC
CBD
CDB
DCB
DBC
ABCD
ABDC
ACBD
ACDB
ADCB
ADBC
BACD
BADC
BCAD
BCDA
BDCA
BDAC
CBAD
CBDA
CABD
CADB
CDAB
CDBA
DBCA
DBAC
DCBA
DCAB
DACB
DABC