1

我有一個問題列出重複排列,維護這個「風格」,遞歸函數。在二維數組中重複排列的列表

例如具有2元件,「AB」和「CD」,在2D陣列:

Element[0][0] = A; Element[0][1] = B; // AB  
Element[1][0] = C; Element[1][1] = D; // CD 

我希望得到所有n個元素的重複可能的排列(在這種情況下2)代入K組(在這種情形2),並將其保存到新的2D陣列 例如在:

Permutation[0][0] = AB; Permutation[0][1] = AB; // 1°: AB,AB 
Permutation[1][0] = AB; Permutation[1][1] = CD; // 2°: AB,CD 
Permutation[2][0] = CD; Permutation[2][1] = AB; // 3°: CD,AB 
Permutation[3][0] = CD; Permutation[3][1] = CD; // 4°: CD,CD 

元和置換必須是二維陣列。 我試過這種方式,但它只有2元的置換工程分爲2組,我被鎖:

int i_perm = 0; 
    int i_element = 0; 
    int k_tot = 2; // number of groups 

    [...] 

    calcPerms(2); 

    [...] 

    private void calcPerms(int k) 
    { 
     if (k == 0) 
     { 
      if(i_perm + 1 < i_perm) 
       i_perm++; 

      i_element=0; 
     } 
     else 
     { 
      for (int i = 0; i < element.length; i++) 
      { 
       Permutation[i_perm][i_element][0] = Element[i][0]; 
       Permutation[i_perm][i_element][1] = Element[i][1]; 

       if(i_element + 1 < k_tot) 
        i_element++; 

       calcPerms(k - 1); 

       if(i_perm >= i_perm) 
        i_perm--; 

       Permutation[i_perm][i_element][0] = Element[i][0]; 
       Permutation[i_perm][i_element][1] = Element[i][1]; 
       if(i_element + 1 < k_tot) 
        i_element++; 
      } 
     } 
    } 

這工作,如上面提到的,僅在第2組2個元素的排列,返回正確:

ABAB,ABCD,CDAB,CDCD。

事實上,如果我把3個元素(第3元素是EF),它返回:

ABAB,ABCD,CDEF,EFAB,ABCD,CDEF,EFAB,ABCD,EFEF

代替:

ABAB,ABCD,ABEF,CDAB,CDCD,CDEF,EFAB,EFCD,EFEF

我怎樣才能得到我想要什麼?謝謝大家的幫助,我的英語不好

+0

一些注意事項:A)這是 「Java」 的不是Java。 B)你的問題的標籤標識所涉及的語言,所以沒有必要把它放在標題中。 – tadman

+1

對不起!感謝您的建議 – Doublem

+0

沒什麼大不了的,只是想讓這個問題更適合網站的格式。 – tadman

回答

0

道歉,你需要的是Heap's Algorithm

有一個在維基百科的鏈接頁面清晰的僞代碼實現。

非遞歸版本看起來像這樣

procedure generate(n : integer, A : array of any): 
    c : array of int 

    for i := 0; i < n; i += 1 do 
     c[i] := 0 
    end for 

    output(A) 

    i := 0; 
    while i < n do 
     if c[i] < i then 
      if i is even then 
       swap(A[0], A[i]) 
      else 
       swap(A[c[i]], A[i]) 
      end if 
      output(A) 
      c[i] += 1 
      i := 0 
     else 
      c[i] := 0 
      i += 1 
     end if 
    end while 
+0

非常好的代碼,但不幫助我。 堆的算法是排列沒有重複,如: ABC,BAC,CAB,ACB,BCA,CBA。 我需要重複排列,如: AAA AAB AAC ABA ABB ABC ACA ACB ACC BAA [...] – Doublem