2012-10-01 27 views
5

可能重複:
generate strings with all permutation of character遞歸置換生成的字符

我在C++初學者,我真的需要你的幫助。我正在使用遞歸進行排列程序。這是我的代碼,但輸出很奇怪,有相同的數字重複許多次和空格。我無法找出問題所在,或者我需要添加更多。請幫幫我。這裏是我的代碼:

#include <iostream> 
using namespace std; 
#define swap(x,y,t) ((t)=(x), (x)=(y), (y)=(t)) 
void perm(char *list, int i, int n); 

int main(){ 
    char a[4]={'a','b','c'}; 
    perm(a,0,3); 
    //cout<<a<<endl;  
    return 0; 
} 

void perm(char *list, int i, int n){ 
    int j, temp; 
    if (i==n){ 
     for (j=0; j<=n; j++) 
      printf("%c", list[j]); 
     printf("  "); 
    } 
    else { 
     for (j=i; j<=n; j++){ 
      swap(list[i],list[j],temp); 
      perm(list,i+1,n); 
      swap(list[i],list[j],temp); 
      cout<<list<<endl; 
     } 
    } 
} 
+0

您只需使用內置''的'next_permutation'功能爲自己節省很多的麻煩。 –

回答

1

該函數是正確的,但你沒有正確調用它。

perm(a,0,3); 

應該

perm(a,0,2); 

爲什麼?

您的循環:

for (j=i; j<=n; j++){ 

去,直到n,所以n應該是一個有效的索引。

Works fine

+0

非常感謝您的回覆^^))) – bionian