Algorithm 这个字符串排列是如何工作的

Algorithm 这个字符串排列是如何工作的,algorithm,recursion,permutation,Algorithm,Recursion,Permutation,需要帮助理解第二次交换调用的正确性 /* 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 ==

需要帮助理解第二次交换调用的正确性

/* 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?
       }
   }
}
/*用于打印字符串排列的函数
此函数采用三个参数:
1.一串
2.字符串的起始索引
3.字符串的结束索引*/
无效排列(字符*a,整数i,整数n)
{
int j;
如果(i==n)
printf(“%s\n”,a);
其他的
{

对于(j=i;j命题:对于长度
>n
的所有
a
(因此
n
是一个有效的索引)而
0你有没有给这段代码做过一次手工演练?用归纳法证明它。对于
i==n-1
,这显然是正确的。如果对某些
0
是正确的,那么对于
i-1
@blacksplane也是正确的。我做了一些等效的事情:添加printf。这表明
置换调用似乎确实保留了
a
在调用前后。现在,我无法证明原因。@DanielFischer。这是我遇到问题的归纳案例。鉴于中间的
置换
可能无法保留
a
,我如何知道第二次
交换
撤消第一次
交换
permute(a, i, n)
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?
}