Print all the permutations of a string in C

前端 未结 8 1473
自闭症患者
自闭症患者 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 04:50

    # include 
    
    /* Function to swap values at two pointers */
    void swap (char *x, char *y)
    {
         char temp;
         temp = *x;
         *x = *y;
         *y = temp;
    }
    
    /* Function to print permutations of string
        This function takes three parameters:
        1. String
        2. Starting index of the string
        3. Ending index of the string. */
    void permute(char *a, int i, int n)
    {
        int j;
        if (i == n)
          printf("%s\n", a);
        else
        {
              for (j = i; j <= n; j++)
             {
                 swap((a+i), (a+j));
                 permute(a, i+1, n);
                 swap((a+i), (a+j)); //backtrack
             }
        }
    }
    
    /* Driver program to test above functions */
    int main()
    {
        char a[] = "ABC";
        permute(a, 0, 2);
        getchar();
        return 0;
    }
    

提交回复
热议问题