2013-07-14 33 views
1

我製作了一個程序,它接收一串字符並打印出所有可能的組合。但是,有沒有辦法將每個組合列入一個列表或一個數組中,而不是將它們打印在屏幕上?因爲我需要能夠操縱一些組合,而不是僅僅看着它們。C - 在數組或列表中打印組合

void swap(char *a, char *b){ 
    char tmp; 
    tmp = *a; 
    *a = *b; 
    *b = tmp; 
} 

void permutation(char *c, int d, int e){ 
    int f; 

    if(d == e) 
     printf("%s\n", c); 
    else{ 
     for(f = d; f <= e; f++){ 
      swap((c + d), (c + f)); 
      permutation(c, d + 1, e); 
      swap((c + d), (c + f)); 
     } 
    } 
} 

int main(){ 
    char wordInput[25]; 
    int len, arrLen, f; 

    printf("\nEnter text: "); 
    gets(wordInput); 
    len = strlen(wordInput); 
    arrLen = len - 1; 

    permutation(wordInput, 0, arrLen); 

    return 0; 
} 
+0

提示:假設我們有一個字母是'k'個字母,那麼排列的數量就是'k! = k(k-1)(k-2)...(3)(2)(1)'所以你需要一個字符串數組(k個字母長),它的大小是k!因此,首先使用strlen計算長度,然後使用malloc分配數組,然後使用任何你喜歡的(遞歸是可以的)填充數組和瞧。嘗試使用此提示創建程序。如果遇到問題,會進一步幫助:-) –

回答

0

只要改變permuation()爲以下:

int permutation(char *c, int d, int e, int n, char **permuted_strings) 

其中n是下一個未使用元素的在陣列permuted_strings的索引。 permuted_strings應該是一個k數組!元素如果你的字符串長度爲k,如註釋中所示。如果符合條件(d == e),則應將該字符串保存在permuted_strings [n]中並將n加1,並將此值作爲n的新值返回。 permutation()函數應該始終返回n的當前值,並且在調用時應將n重置爲permutation()的返回值,以便隨後對permutation()的調用知道n的正確值,即在何處存儲下一個字符串。