我无法理解此代码的工作原理

时间:2014-10-09 06:05:44

标签: c string

这是一个c程序,用于找出所有可能的单词组合 - >

# include <stdio.h>

/* 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;
}

任何人都可以解释一下排列代码部分是如何工作的吗?提前谢谢

2 个答案:

答案 0 :(得分:1)

拿这段代码运行它,懒得写所有的阶段,为什么不让电脑去做呢?

# include <stdio.h>

/* Function to swap values at two pointers */
void swap (char *x, char *y)
{
    char temp;
    printf("Swapping %c with %c\n",*x,*y); //<---------- I ADDED THIS FOR YOU
    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;
   printf("-----Now in permute(a,%d,%d)-----\n",i,n); //<---------- I ADDED THIS FOR YOU
   printf("-----String is now %s-----\n",a); //<---------- I ADDED THIS FOR YOU
   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;
}

答案 1 :(得分:0)

也许你在理解回溯技术时遇到了问题。在这种情况下,您应该阅读一些内容:http://en.wikipedia.org/wiki/Backtracking

然而,代码从位置0处的char到以下2个字符的作用。 它使用下面的内容更改第一个char,并以下一个char作为起点调用自身。最后切换回字符以重新创建orign情况。

在递归的第一级,该函数正在切换第一个字母并为接下来的两个字母调用自身:

permute("ABC", 1, 2)
permute("BAC", 1, 2)
permute("CBA", 1, 2)

第二级递归:

permute("ABC", 2, 2) /* -> printf ABC */
permute("ACB", 2, 2) /* -> printf ACB */

permute("BAC", 2, 2) /* -> printf BAC */
permute("BCA", 2, 2) /* -> printf BCA */

permute("CBA", 2, 2) /* -> printf CBA */
permute("CAB", 2, 2) /* -> printf CAB */