Print all permutation in lexicographic order

前端 未结 9 2038
悲哀的现实
悲哀的现实 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:47

    IMHO, it would be simpler to first sort the characters of the string because the number of permutations (n!) is always greater (or equal for n = 1 or 2) than the number of characters.

    And you were not far from the solution but you must rotate instead of swap. Here is a slight variation that returns an array of dynamically allocated strings that are printed in the main :

    #include 
    #include 
    #include 
    
    int char_compare(const void *a, const void *b) {
        return (*((char *) a)) - (*((char *) b));
    }
    
    int fact(int n) {
        int f = 1;
        while (n > 0) {
            f *= n--;
            if (f < 0) return 0;
        }
        return f;
    }
    
    void rotateback(char *a, int i, int j) {
        int k;
        char tmp;
        tmp = a[i];
        for(k=i; ki; k--) {
            a[k] = a[k-1];
        }
        a[i] = tmp;
    }
    
    void permute(char *a, int i, int n, char ***permuts) {
        int j;
        if (i == (n-1)) {
            **permuts = strdup(a);  // store a copy of the string
            *permuts += 1;          // and point to next location
        }
       else {
           for (j = i; j < n; j++) {
               rotate(a, i, j);
               permute(a, i+1, n, permuts);
               rotateback(a, i, j);
           }
       }
    }
    char ** permutations(const char *str_orig) {
        int i, j;
        size_t n = strlen(str_orig);
        size_t fact_n = fact(n);
        char ** permuts, **work;
    
        char * str = strdup(str_orig); // get a local copy
        qsort(str, n, 1, char_compare); // and sort it
    
        permuts = work = calloc(fact_n, sizeof(char *)); // allocate n! pointers
    
        permute(str, 0, n, &work);
        return permuts;
    }
    
    int main() {
        char str[] = "cab";
        int i;
    
        char **permuts = permutations(str);
    
        for (i=0; i

    Output is correctly :

    "abc"
    "acb"
    "bac"
    "bca"
    "cab"
    "cba"
    

提交回复
热议问题