有人可以建议我对我的代码进行必要的更改吗?

时间:2016-10-22 16:16:31

标签: c recursion permutation

排列,也称为“排列号”或“顺序”,是将有序列表S的元素重新排列成与S本身一一对应的。一个长度为n的字符串有n!排列。 以下是字符串ABC的排列。 ABC ACB BAC BCA CBA CAB

所有可能的字符串排列的以下代码都使用回溯编码,但它不起作用,请任何人建议进行必要的更改。

C程序打印允许重复的所有排列 -

 #include <stdio.h>
 #include <string.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 l, int r)
{
   int i;
   if (l == r)
     printf("%s\n", a);
   else
   {
       for (i = l; i <= r; i++)
      {
         swap((a+l), (a+i));
         permute(a, l+1, r);
         swap((a+l), (a+i)); //backtrack
       }
   }
 }

 /* Driver program to test above functions */
 int main()
{
    char str[] = "ABC";
    int n = strlen(str);
     permute(str, 0, n);
    return 0;
    }

1 个答案:

答案 0 :(得分:1)

这是OBOB(Of By One Bug)的经典案例。

n长度字符串的最后一个字符的索引是n-1,因此当循环遍历字符串中的所有索引时,循环不应该是for (i = l; i <= r; i++),而是for (i = l; i < r; i++)。< / p>

使用索引太大来调用swap()会产生奇怪的效果,例如缩短字符串。

这是更改后的permute()函数:

void permute(char *a, int l, int r)
{
   int i;
   if (l == r)
     printf("%s\n", a);
   else
   {
       for (i = l; i < r; i++)  // corrected indices
      {
         swap((a+l), (a+i));
         permute(a, l+1, r);
         swap((a+l), (a+i)); //backtrack
       }
   }
 }

现在应该可以了。