谁能建议我对我的代码进行必要的更改?
Can anyone suggest me the necessary changes for my code?
排列,也称为“排列数”或“顺序”,是将有序列表 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;
}
这是OBOB(Of By One Bug)的经典案例。
n 长字符串的最后一个字符的索引是 n-1,因此当遍历字符串中的所有索引时,循环不应该是 for (i = l; i <= r; i++)
,而是 for (i = l; i < r; i++)
.
使用太大的索引调用 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
}
}
}
现在应该可以了。
排列,也称为“排列数”或“顺序”,是将有序列表 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;
}
这是OBOB(Of By One Bug)的经典案例。
n 长字符串的最后一个字符的索引是 n-1,因此当遍历字符串中的所有索引时,循环不应该是 for (i = l; i <= r; i++)
,而是 for (i = l; i < r; i++)
.
使用太大的索引调用 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
}
}
}
现在应该可以了。