2015-12-02 73 views
-2

我是C#的初學者,我正在尋找一個代碼來返回一組集合的所有可能的排列,例如{1,1,2},沒有重複{112,121,211}。我找到了以下鏈接,但我不知道如何使用它。無重複排列C#

http://www.codeproject.com/Articles/26050/Permutations-Combinations-and-Variations-using-C-G

我曾嘗試的代碼如下。例如,當我嘗試獲取「111」的排列組合時,它會返回所有可能的排列組合,即六個111。但我正在尋找一些提供排列而不重複的東西。更詳細地說,111只是一個排列而不是六個排列。

class Program 
{ 
    private static void Swap(ref char a, ref char b) 
    { 
     if (a == b) return; 

     a ^= b; 
     b ^= a; 
     a ^= b; 
    } 

    public static void GetPer(char[] list) 
    { 
     int x = list.Length - 1; 
     GetPer(list, 0, x); 
    } 

    private static void GetPer(char[] list, int k, int m) 
    { 
     if (k == m) 
     { 
      Console.Write(list); 
     } 
     else 
      for (int i = k; i <= m; i++) 
      { 
        Swap(ref list[k], ref list[i]); 
        GetPer(list, k + 1, m); 
        Swap(ref list[k], ref list[i]); 
      } 
    } 

    static void Main() 
    { 
     string str = "sagiv"; 
     char[] arr = str.ToCharArray(); 
     GetPer(arr); 
    } 
} 
+0

先打在谷歌搜索 - http://stackoverflow.com/questions/756055/listing-all-permutations-of-a-string-integer – JamieMeyer

+0

我試過了,但是當我測試「11123344」或「111」 –

+0

{1,1,2}不是一組時,它會返回錯誤的解決方案。 –

回答

0

既然您還沒有發佈任何代碼,只能猜測。但是,如果你將問題陳述分解開來,那麼聽起來好像你只有一個問題,那就是重複你的輸入。這是一個微不足道的問題。這裏有一種方法:

string dedupe = new string(input.ToCharArray().Distinct().ToArray()); 

字符串重複數據刪除現在只包含原始字符串輸入中的唯一字符。

0

我終於找到了我正在尋找的代碼。

公共靜態無效的置換(INT [] PS,詮釋開始,詮釋N) {

//doSomething(ps); 
int tmp = 0; 
if (start < n) { 
    for (int i = n - 2; i >= start; i--) { 
    for (int j = i + 1; j < n; j++) { 
     if (ps[i] != ps[j]) { 
     // swap ps[i] <--> ps[j] 
     tmp = ps[i]; 
     ps[i] = ps[j]; 
     ps[j] = tmp; 

     permute(ps, i + 1, n); 
     } 
    } 

    // Undo all modifications done by 
    // recursive calls and swapping 
    tmp = ps[i]; 
    for (int k = i; k < n - 1;) 
     ps[k] = ps[++k]; 
    ps[n - 1] = tmp; 
    } 
} 

}