需要帮助理解第二次交换调用的正确性。
/* 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)); // how does this work here?
}
}
}
似乎第二次交换是为了撤消第一次交换。但是我看不到为什么中间permute
调用会保留原始调用*(a+i)
保持在a+j
.
笔记:
[1] 代码位于http://www.geeksforgeeks.org/write-ac-program-to-print-all-permutations-of-a-given-string/