2014-10-09 88 views
-6

這是一個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; 
} 

誰能請解釋我是如何排列的代碼部分工作?在此先感謝

+3

對於像「ABC」這樣的小字符串,您可以使用鉛筆和紙張輕鬆解決。 – 2014-10-09 06:06:42

+0

閱讀關於遞歸,指針並學習使用調試器。 – user1336087 2014-10-09 06:17:23

回答

0

也許你有理解回溯技術的問題。在這種情況下,您應該讀一點關於它的內容:http://en.wikipedia.org/wiki/Backtracking

但是,代碼從位置0處的字符起直至2個字符後才起作用。 它用下面的內容改變第一個字符,並用下一個字符作爲起點調用它自己。最後切回字符重新創建狀態。

在遞歸功能切換的第一個字母,並調用自身在未來兩年的第一級:

permute("ABC", 1, 2) 
permute("BAC", 1, 2) 
permute("CBA", 1, 2) 

遞歸的第二個層次:

permute("ABC", 2, 2) /* -> printf ABC */ 
permute("ACB", 2, 2) /* -> printf ACB */ 

permute("BAC", 2, 2) /* -> printf BAC */ 
permute("BCA", 2, 2) /* -> printf BCA */ 

permute("CBA", 2, 2) /* -> printf CBA */ 
permute("CAB", 2, 2) /* -> printf CAB */ 
1

把這個代碼並運行它,懶得寫出所有的階段爲什麼不讓電腦做到這一點?

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