Print all permutation in lexicographic order

前端 未结 9 2050
悲哀的现实
悲哀的现实 2020-11-30 10:04

I want to print all permutation of string in lexicographic order. I wrote this code:

void permute(char *a, int i, int n) {
   if (i == (n-1)) printf(\"\\\"%s         


        
9条回答
  •  无人及你
    2020-11-30 10:38

    This is voluntarily an answer that does not answer this question.

    This other question was marked as a duplicate to this one. This answer would be acceptable for the other question even if it is non sense here.

    This could be a simple recursive C implementation to get all permutations in lexicographic order. It is not optimized but easy to understand and to implement:

    • get an array for the elements to permute
    • at any step, iterate through the elements that have not been used until here
      • add one of the iterated elements to the array of used elements
      • recurse
    • when the array of used element is full print it.

    Concrete implementation:

    #include 
    
    #define SIZE 4
    
    void disp(int *fullarr, int n, int * begin, int pos) {
        int i, j;
        int found;
        if (pos == n) {
            for(i=0; i< n; i++) {
                printf("%2d", begin[i]);
            }
            printf("\n");
            return;
        }
        for (i=0; i

提交回复
热议问题