问题描述
我是编程新手,我正在尝试用 C 补充这段代码以置换字符串,目前它显示所有交换的单词并计算单词有多少个字符。
但我也希望它计算排列生成的行数,在这部分代码不起作用。我不知道还能做什么!
示例:单词“hi”生成两行:hi 和 ih。 (在这种情况下,我希望程序写入“生成的单词:2”)
代码:
#include <string.h>
#include <stdio.h>
void swap (char *x,char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
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
}
}
}
int main()
{
char str[21];
int len;
int cont = 1;
int fatorial = 1;
printf("\nType a word: ");
scanf("%s",str);
len = strlen(str);
permute(str,len - 1);
printf("\nNumber of letters: %d\n",len);
while (cont < len)
{
fatorial = fatorial * cont;
cont++;
}
printf("\nPossibilities:%d",fatorial);
return 0;
}
解决方法
您可以在 Node(10,20,30)
中增加一个计数器。类似的东西:
permute