2016-10-23 22 views
0
void per(int count){ 

    if(count==l){ 
     printf("%s\n", p); 
     return; 
    } 

    for(int i=0;i<l;i++){ 
      if(visit[i]==0){ 
      visit[i]=1; 
      p[count]=arr[i]; 
      per(count+1); 
      visit[i]=0; //backtrack 
      } 
    } 
} 

上面提到的代碼是爲字符串「aab」生成以下排列組合。帶重複字符的字符串排列(訪問數組概念)

aab 
aba 
aab 
aba 
baa 
baa 

一些排列的字符串會重複嗎?我怎樣才能減少它? 鏈接到我的code

+1

而不是打印每個排列的,你可以將它們存儲在一個列表,並在年底刪除重複。 –

回答

1

您正在使用C++,因此std:next_permutation是您最好的朋友。

如果要從零開始實施排列,請使用algorithm description for the next lexicographic permutation。請注意,算法適用於重複元素。

Find the largest index k such that a[k] < a[k + 1]. If no such index exists, 
    the permutation is the last permutation. 

Find the largest index l greater than k such that a[k] < a[l]. 

Swap the value of a[k] with that of a[l]. 

Reverse the sequence from a[k + 1] up to and including the final element a[n]. 

任意C++