Print all the permutations of a string in C

前端 未结 8 1452
自闭症患者
自闭症患者 2020-11-29 04:06

I am learning backtracking and recursion and I am stuck at an algorithm for printing all the permutations of a string. I solved it using the bell algorithm for permutation b

8条回答
  •  一整个雨季
    2020-11-29 04:58

    The code has 2 problems, both related to n, the assumed length of the string. The code for (j = i; j <= n; j++) { swap((a+i), (a+j)); ... swap in string's null character '\0' and gives code truncated results. Check the original (i == n) which should be (i == (n-1)).

    Backtracking is applied by calling swap() twice effective undoing its original swap.

    The order of complexity is the same for Bell Algorithm.

    #include 
    
    void swap(char *a, char *b) { char t = *a; *a = *b; *b = t; }
    
    void permute(char *a, int i, int n) {
       // If we are at the last letter, print it
       if (i == (n-1)) printf("%s\n", a);
       else {
         // Show all the permutations with the first i-1 letters fixed and 
         // swapping the i'th letter for each of the remaining ones.
         for (int j = i; j < n; j++) {
           swap((a+i), (a+j));
           permute(a, i+1, n);
           swap((a+i), (a+j));
         }
      }
    }
    
    char s[100];
    strcpy(s, "ABCD");
    permute(s, 0, strlen(s));
    

提交回复
热议问题