Backtracking如何在此代码中工作

时间:2014-07-10 06:07:13

标签: c++ recursion

我无法理解permute功能是如何工作的。每次我都找不到实际的置换功能,以及为什么它被称为回溯????

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

2 个答案:

答案 0 :(得分:1)

这个特定的实现起到了观察,序列{a,b,c,d,e,...}的所有排列的集合可以描述如下:

所有以'a'开头的序列:{a,...},所有以'b'开头的序列:{b,...}等。 所有以'a'开头的序列({a,x,y,z,...}}只是一个'a',后跟{x,y,z,...}的所有可能序列(以及是递归部分。)

回溯是指算法从给定的部分解({a,x,y,z})开始然后“进入”解决尚未解决的部分({x,y,z})然后去回到先前给定的情况不再给定但会改变的情况(从{a,x,y,z}变为{b,...},{c,...})

答案 1 :(得分:0)

//Swapping two characters
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)
    //This is an edge case where (i==j==n) and hence no swap needed (recursion terminates).
    printf("%s\n", a);
    else
    {
        for (j = i; j <= n; j++)
     {
          swap((a+i), (a+j));
          permute(a, i+1, n);
          /*Basically recursion terminated for first set of swapping 
          and then get back the original array by backtracking to apply second set of swapping. 
          Then iterating this procedure for all sets of swapping will 
          give all the permutations of the given set of characters*/
          swap((a+i), (a+j));
       }
   }
}