gpt4 book ai didi

c - 我无法理解这段代码是如何工作的

转载 作者:行者123 更新时间:2023-11-30 21:44:02 26 4
gpt4 key购买 nike

这是一个 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;
}

谁能解释一下排列代码部分是如何工作的?提前致谢

最佳答案

拿这段代码来运行它,懒得写所有阶段为什么不让计算机来做呢?

# 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;
}

关于c - 我无法理解这段代码是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26271399/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com